我有一个平面的对象数组,我想将其与对象的子数组

时间:2019-07-16 21:32:20

标签: javascript arrays object nested hierarchy

我想合并两个具有此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

2 个答案:

答案 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)