我有对象A。我想用对象B的更改来更新这个对象。
- 如果对象B中不存在字段,则应保持不变
- 如果对象B中有一个字段不存在于对象a中,则最好不添加该字段,但如果这将简化解决方案,则可以添加该字段
例如
o1 = {[
{
key: "A",
content: {
field1: "sample text A",
field2: "another sample text A"
}
},
{
key: "B",
content: {
field1: "sample text B",
field2: "another sample text B"
}
}
]}
o2 = [{
key: "A",
content: {
field1: "updated sample text A",
field3: "added text A"
}
}]
输出:
o3 = {[
{
key: "A",
content: {
field1: "updated sample text A",
field2: "another sample text A"
}
},
{
key: "B",
content: {
field1: "sample text B"
field2: "another sample text B"
}
}
]}
使用Object.assign((
我刚刚测试过:
let o1 = [
{
key: "A",
content: {
field1: "sample text A",
field2: "another sample text A"
}
},
{
key: "B",
content: {
field1: "sample text B",
field2: "another sample text B"
}
}
]
let o2 = [{
key: "A",
content: {
field1: "updated sample text A",
field3: "added text A"
}
}]
Object.assign(o1, o2);
console.log(o1);
获得输出:
[
{
key: 'A',
content: { field1: 'updated sample text A', field3: 'added text A' }
},
{
key: 'B',
content: { field1: 'sample text B', field2: 'another sample text B' }
}
]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
编辑-我发现这个功能可以满足您的需要,而不仅仅是覆盖属性。
function realMerge(to, from) {
for (let n in from) {
if (typeof to[n] != 'object') {
to[n] = from[n];
} else if (typeof from[n] == 'object') {
to[n] = realMerge(to[n], from[n]);
}
}
return to;
};
我在这里测试了输出,它产生了:
[
{
key: 'A',
content: {
field1: 'updated sample text A',
field2: 'another sample text A',
field3: 'added text A'
}
},
{
key: 'B',
content: { field1: 'sample text B', field2: 'another sample text B' }
}
]