假设我有两个对象object_one
{
1: {item1 /*updated*/}, //note updated represents more recent item1 data
2: {item1 /*updated*/},
3: {item1 /*updated*/}
}
和object_two
{
1: {item1, item2, item3},
2: {item1, item2, item3},
4: {item1, item2, item3},
5: {item1, item2, item3}
}
我想将object_one
添加到object_two
,添加object_two
没有的任何元素。我还想使用{1}}版本的item1并将其更新为object_two
' s
期望的结果
object_one
我自己尝试过这样做,但我的解决方案是手动的,并且不适用于{
1: {item1 /*updated*/, item2, item3},
2: {item1 /*updated*/, item2, item3},
3: {item1 /*updated*/},
4: {item1, item2, item3},
5: {item1, item2, item3}
}
和object_one
的所有长度。我们非常感谢某些方向
答案 0 :(得分:3)
有关详细信息,请参阅Object.entries
和Object.assign
。
// Original.
const original = {
1: {A: '1A', B: '1B', C: '1C'},
2: {A: '2A', B: '2B', C: '2C'},
4: {A: '4A', B: '4B', C: '4C'},
5: {A: '5A', B: '5B', C: '5C'}
}
// Merge.
const update = {
1: {A: '1A updated'},
2: {B: '2B updated'},
3: {C: '3C updated'}
}
// Combine.
const merge = (original, update) => {
const x = {...original}
Object.entries(update).forEach(([key, value]) => {
x[key] = Object.assign({}, x[key], value)
})
return x
}
// Output.
const output = merge(original, update)
// Proof.
console.log(output)