gpt4 book ai didi

javascript - 根据不同的键但相同的值合并 2 个对象数组

转载 作者:行者123 更新时间:2023-11-28 14:18:15 26 4
gpt4 key购买 nike

我已经提交了下面列出的问题,但没有得到相关答案。

  1. How can I merge properties of two JavaScript objects dynamically?
  2. merge two json object based on key value in javascript
  3. Merge two array of objects based on a key

我有 2 个对象数组,

OBJ1 -

[
{
"ID": 58895,
"step": "Outage Agreed w/ Business"
},
{
"ID": 58896,
"step": "GMLC/E911/CMAS Significant"
}
]

OBJ2 -

[
{
"type": "verification_step",
"value": "GMLC/E911/CMAS Significant"
},
{
"type": "verification_step",
"value": "Outage Agreed w/ Business"
}
]

我希望输出包含基于字符串值的单个对象中的两个值,即

[
{
"ID": 58896,
"type": "verification_step",
"step": "GMLC/E911/CMAS Significant"
},
{
"ID": 58895,
"type": "verification_step",
"step": "Outage Agreed w/ Business"
}
]

请给我建议出路。 (ES6 解决方案 - 非常感谢)

编辑

被指定为重复的第三个引用不是这种情况。键应保持“step”并且数据应合并。

最佳答案

合并两个数组后,您可以使用reduce()

const arr1 = [ { "ID": 58895, "step": "Outage Agreed w/ Business" }, { "ID": 58896, "step": "GMLC/E911/CMAS Significant" } ] 

const arr2 = [ { "type": "verification_step", "value": "GMLC/E911/CMAS Significant" }, { "type": "verification_step", "value": "Outage Agreed w/ Business" } ]

const res = [...arr1,...arr2.map(({value,...rest}) => ({step:value,...rest}))].reduce((ac,a) => {
let k = a.step;
ac[k] = {...ac[k],...a} || a;
return ac;
},{})
console.log(Object.values(res))

关于javascript - 根据不同的键但相同的值合并 2 个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56447582/

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