新对象和旧对象对比,如果旧对象包含老对象变量,则改变老对象的值
var table1 = {
name: "张三",
age: 18,
config: {
a: 1
},
config1: [1, 222222, 2, 3]
};
var table2 = {
page:1,
name: null,
age: 0,
code: 18,
config: {
a: 2
},
config1: [1, 2, 3]
}
function merge(newData, oldData) {
if (newData instanceof Object) {
for (const key in newData) {
if (oldData.hasOwnProperty(key)) {
oldData[key] = newData[key]
merge(newData[key], oldData[key])
}
}
}
return oldData
}
console.log(merge(table1, table2));
还有一种情况,新对象相同的改变,没有的也要;前提是新数据中有老数据中没有的,但提交要按老数据;虽然有点绕但是有可能会有这种场景
var table1 = {
name: "张三",
age: 18,
config: {
a: 1
},
config1: [1, 222222, 2, 3],
wang:1
};
var table2 = {
page:1,
name: null,
age: 0,
code: 18,
config: {
a: 2
},
config1: [1, 2, 3]
}
function mergeAll(newData, oldData) {
if (newData instanceof Object) {
for (const key in newData) {
if (oldData.hasOwnProperty(key)) {
oldData[key] = newData[key]
mergeAll(newData[key], oldData[key])
}else{
oldData[key] = newData[key]
}
}
}
return oldData
}
console.log(mergeAll(table1, table2));
网友评论