gpt4 book ai didi

javascript - 组合数组并插入差异

转载 作者:行者123 更新时间:2023-11-29 18:55:29 25 4
gpt4 key购买 nike

假设我有两个对象,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 没有的任何元素。我还想获取 object_two 的 item1 版本并将它们更新为 object_one 的值

想要的结果

{
1: {item1 /*updated*/, item2, item3},
2: {item1 /*updated*/, item2, item3},
3: {item1 /*updated*/},
4: {item1, item2, item3},
5: {item1, item2, item3}
}

我自己尝试过,但我的解决方案是手动的,不适用于 object_oneobject_two 的所有长度。一些方向将不胜感激

最佳答案

参见 Object.entriesObject.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com