Default props for objects in array

by dekkard

JavaScript

var keysSet = new Set();
var pushWithFill = function(arr, newObject) {
    // add keys from the new obj to the dictionary
    // and add missing properties to this object
    keysSet.forEach(function(key){
        if (!newObject.hasOwnProperty(key)) {
            newObject[key] = '';
        }
    });
    for (var property in newObject) {
        keysSet.add(property);
    }
    
    // process all stored objects to add keys from the new one to them
    arr.forEach(function(storedObj, index){
        for (var property in newObject) {
             if (!storedObj.hasOwnProperty(property)) {
                    storedObj[property] = '';
             } 
        }
    });
    
    arr.push(newObject);
};


var arr = [];

var obj_1 = {
    'key_a': 'value_a',
    'key_b': 'value_b'
};
var obj_2 = {
    'key_a': 'value_a',
    'key_b': 'value_b',
    'key_c': 'value_c'
};
var obj_3 = {
    'key_a': 'value_a'
}

pushWithFill(arr, obj_1);
pushWithFill(arr, obj_2);
pushWithFill(arr, obj_3);

console.log(JSON.stringify(arr));