You could use a deep merge function for every level of the object.
The function deepMerge works as single function for a given target or as callback for Array#reduce, where an array of objects is iterated and an empty object is supplied as startvalue for reducing.
The function/callback itselft has two parameters, one for the target object and one for the source object where all entries are taken and iterated.
A value of the object is checked and if the type is an object, then a recursive call of deepMerge is done with a a new target property, if not given or to an exitent property.
If the value is not an object, the value is assigned to target with the given key.
The result is a new object with all properties of the given objects.
function deepMerge(target, source) {
Object.entries(source).forEach(([key, value]) => {
if (value && typeof value === 'object') {
deepMerge(target[key] = target[key] || {}, value);
return;
}
target[key] = value;
});
return target;
}
var a = { prop: { a: '1' } },
b = { prop: { b: '1' } },
c = [a, b].reduce(deepMerge, {});
console.log(c);
c === a, because ofObject.assign. do you want a new object or assign toa?mergefrom Lodash. lodash.com/docs#merge