【发布时间】:2018-03-15 16:31:07
【问题描述】:
我有以下数组:
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;
}, []);
任何帮助将不胜感激。提前致谢。
【问题讨论】:
-
您的数组格式无效,..(ps:抱歉编辑,我回滚了,是偶然的)
-
“相同的键值对”是指具体的
id、name和type,还是“everything-but-nodes”,或者其他什么? -
是的。我刚刚编辑了问题
-
我认为你可以使用 for in/as 循环函数来管理它......类似这样的伪代码:for obj in array for(i=0;i
标签: javascript arrays object lodash