如果您想合并多个普通对象(不要修改输入对象)。基于对象。分配polyfill
function isPlainObject(a) {
return (!!a) && (a.constructor === Object);
}
function merge(target) {
let to = Object.assign({}, target);
for (let index = 1; index < arguments.length; index++) {
let nextSource = arguments[index];
if (nextSource !== null && nextSource !== undefined) {
for (let nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
if (isPlainObject(to[nextKey]) && isPlainObject(nextSource[nextKey])) {
to[nextKey] = merge(to[nextKey], nextSource[nextKey]);
} else {
to[nextKey] = nextSource[nextKey];
}
}
}
}
}
return to;
}
// Usage
var obj1 = {
a: 1,
b: {
x: 2,
y: {
t: 3,
u: 4
}
},
c: "hi"
};
var obj2 = {
b: {
x: 200,
y: {
u: 4000,
v: 5000
}
}
};
var obj3 = {
c: "hello"
};
console.log("result", merge(obj1, obj2, obj3));
console.log("obj1", obj1);
console.log("obj2", obj2);
console.log("obj3", obj3);
如果你想合并有限的深度
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) {
// Avoid bugs when hasOwnProperty is shadowed
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;
}
// Usage
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));