function isPlainObject(a) {
return (!!a) && (a.constructor === Object);
}
function merge(target) {
let to = Object.assign({}, target);
const hasDepth = arguments.length > 2 && typeof arguments[arguments.length - 1] === 'number';
const depth = hasDepth ? arguments[arguments.length - 1] : Infinity;
const lastObjectIndex = hasDepth ? arguments.length - 2 : arguments.length - 1;
for (let index = 1; index <= lastObjectIndex; index++) {
let nextSource = arguments[index];
if (nextSource !== null && nextSource !== undefined) {
for (let nextKey in nextSource) {
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
if (depth > 0 && isPlainObject(to[nextKey]) && isPlainObject(nextSource[nextKey])) {
to[nextKey] = merge(to[nextKey], nextSource[nextKey], depth - 1);
} else {
to[nextKey] = nextSource[nextKey];
}
}
}
}
}
return to;
}
var obj1 = {
a: 1,
b: {
x: 2,
y: {
t: 3,
u: 4,
z: {zzz: 100}
}
},
c: "hi"
};
var obj2 = {
b: {
y: {
u: 4000,
v: 5000,
z: {}
}
}
};
var obj3 = {
c: "hello"
};
console.log('deep 0', merge(obj1, obj2, obj3, 0));
console.log('deep 1', merge(obj1, obj2, obj3, 1));
console.log('deep 2', merge(obj1, obj2, obj3, 2));
console.log('deep 2', merge(obj1, obj2, obj3, 4));
const merge = (p, c) => Object.keys(p).forEach(k => !!p[k] && p[k].constructor === Object ? merge(p[k], c[k]) : c[k] = p[k])
- Xaqronhttps://gist.github.com/ahtcx/0cd94e62691f539160b32ecda18af3d6
- Nwawel A Iroume