假设我有两个对象,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
没有的任何元素。我还想获取item1的object_two
版本并将其更新为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
和object_two
。一些方向将不胜感激 最佳答案
有关更多信息,请参见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)
关于javascript - 合并数组并插入差异,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49623226/