javascript - Add missing properties to an object with a blank value if they don't exist -


i have array of objects different properties:

var arr = [];  var obj_1 = {     'key_a': 'value_a',     'key_b': 'value_b' };  arr.push(obj_1);  var obj_2 = {     'key_a': 'value_a',     'key_b': 'value_b',     'key_c': 'value_c' };  arr.push(obj_2); 

how automatically add new key (key_c), or other key, every object in array blank value if doesn't exist?

so array this:

    [         {             'key_a': 'value_a'             'key_b': 'value_b'             'key_c': ''         },         {             'key_a': 'value_a'             'key_b': 'value_b'             'key_c': 'value_c'         }     ] 

please note: i'm building web scraper , unknown keys/properties added objects , pushed array in foreach loop.

i'd create special object act container. special object storage keys of objects pushed objects.

once user wants retrieve objects it, object update keys of stored objects make sure of them have same keys correct values.

var specialarray = function () {     var keys = object.create(null),         objs = [];      this.push = function (obj) {         (var key in obj) {             if (obj.hasownproperty(key)) {                 keys[key] = true;             }         };          objs.push(obj);         return this;     };      this.toarray = function () {         objs.foreach(function (current) {             (var key in keys) {                 if (current[key] === undefined) {                     current[key] = '';                 }             }         });         return objs;     }; };  var obj1 = {     a: 'hello',     b: 'hello' };  var obj2 = {     a: 'hello',     b: 'hello',     c: 'hola' };  var f = new specialarray; console.log(f.push(obj1).push(obj2).toarray()); 

you can add functionality object improve it.

fiddle

hope helps.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -