gpt4 book ai didi

javascript - 合并具有相同键值对的对象数组中的值

转载 作者:行者123 更新时间:2023-11-30 14:43:37 25 4
gpt4 key购买 nike

我有以下数组:

     const arr = [  
{
id:"aaa",
name:"aaa",
type:"director",
nodes:[
{
type:"manager",
id:"111",
name:"111"
}
]
},
{
id:"aaa",
name:"bbb",
type:"director",
nodes:[
{
type:"manager",
id:"222",
name:"222"
}
]
},
{
id:"aaa",
name:"aaa",
type:"director",
nodes:[
{
type:"manager",
id:"333",
name:"333"
}
]
},
{
id:"aaa",
name:"bbb",
type:"director",
nodes:[
{
type:"manager",
id:"444",
name:"444"
}
]
}
]

期望的输出:

        const arr = [  
{
id:"aaa",
name:"aaa",
type:"director",
nodes:[
{
type:"manager",
id:"111",
name:"111"
},
{
type:"manager",
id:"333",
name:"333"
}
]
},
{
id:"aaa",
name:"bbb",
type:"director",
nodes:[
{
type:"manager",
id:"222",
name:"222"
},
{
type:"manager",
id:"444",
name:"444"
}
]
}

我正在尝试将上述数组中具有相同键值(id、名称和类型)对的节点对象数组的值合并到所需的输出中。

我已经尝试了以下但没有成功的 arr.reduce,但是没有成功:

arr.reduce((acc, el) => {
var existEl = acc.find(e => e.nodes.id === el.nodes.id);
if (existEl) {
existEl = el;
} else {
acc.push(el);
}

return acc;
}, []);

任何帮助将不胜感激。提前致谢。

最佳答案

你可以使用 Map并收集所有具有相同 idname

的项目

var array = [{ id: "aaa", name: "aaa", type: "director", nodes: [{ type: "manager", id: "111", name: "111" }] }, { id: "aaa", name: "bbb", type: "director", nodes: [{ type: "manager", id: "222", name: "222" }] }, { id: "aaa", name: "aaa", type: "director", nodes: [{ type: "manager", id: "333", name: "333" }] }, { id: "aaa", name: "bbb", type: "director", nodes: [{ type: "manager", id: "444", name: "444" }] }],
result = [...array.reduce((m, o) => {
var key = ['id', 'name'].map(k => o[k]).join('|');
if (m.has(key)) {
m.get(key).nodes.push(...o.nodes);
} else {
m.set(key, Object.assign({}, o, { nodes: o.nodes }));
}
return m;
}, new Map).values()];

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 合并具有相同键值对的对象数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49304666/

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