我想合并两个具有此ID的父ID的数组
//parent table
const parent = [{ pid: 1, pname: 'jack' }, { pid: 2, pname: 'jhon' }]
还有这个
//child table
const child = [
{ cid: 1, cname: 'zhina', pid: 1 },
{ cid: 2, cname: 'mandy', pid: 1 },
{ cid: 3, cname: 'henry', pid: 2 },
{ cid: 4, cname: 'jhonny', pid: 2 }
]
此方法=>
//nested table
nested = [{
pid: 1,
pname: 'jack',
children: [
{ cid: 1, cname: 'zhina', pid: 1 },
{ cid: 2, cname: 'mandy', pid: 1 }
]
},
{
pid: 2,
pname: 'jhon',
children: [
{ cid: 3, cname: 'henry', pid: 2 },
{ cid: 4, cname: 'jhonny', pid: 2 }
]
}
]
我不知道使用reduce或对象键或对象分配会更好...对此我表示怀疑。.我很高兴告诉我做这些家伙的最佳方法thnxxxxx
答案 0 :(得分:1)
使用Array.reduce()
迭代child
数组。累加器的初始状态是parent
数组的Map,其对象具有空的子数组。对于每个孩子,如果父亲存在于地图中,则将其作为父亲,然后将孩子推到children
数组中:
const parent = [{pid:1 , pname : 'jack'} , {pid:2 , pname:'jhon'}]
const child = [{"cid":1,"cname":"zhina","pid":1},{"cid":2,"cname":"mandy","pid":1},{"cid":3,"cname":"henry","pid":2},{"cid":4,"cname":"jhonny","pid":2}]
const result = Array.from(child.reduce(
(r, o) => {
if(r.has(o.pid)) r.get(o.pid).children.push(o)
return r
},
new Map(parent.map(o => [o.pid, { ...o, children: [] }]))
).values())
console.log(result)
答案 1 :(得分:1)
这应该做:
const parent = [{pid:1 , pname : 'jack'} , {pid:2 , pname:'jhon'}]
const child = [
{cid:1,cname:'zhina' , pid:1} ,
{cid:2,cname:'mandy' , pid:1} ,
{cid:3,cname:'henry' , pid:2} ,
{cid:4,cname:'jhonny' , pid:2}
]
const result = parent.map(item => {
return {
...item,
children: child.filter(el => el.pid === item.pid)
}
})
console.log(result)