将对象的平面数组转换为嵌套数组

时间:2021-02-16 07:19:01

标签: javascript arrays reactjs

我有一个如下的数组,在这个数组中 creditUsage 数组有具有父子关系但都存在于同一级别的对象

    let subCredits =[
{
   creditNr : "A001"
   creditUsage: [
   {
     id: 1,
     parentId :null
   },
   {
     id: 2,
     parentId :null
   },{
     id: 22,
     parentId :2
   },{
     id: 11,
     parentId :1
   },
   
    ]
},
{
  creditNr : "A002"
   creditUsage:[
   {
     id: 1,
     parentId :null
   },
   {
     id: 2,
     parentId :null
   },{
     id: 22,
     parentId :2
   },{
     id: 11,
     parentId :1
   },
   
    ]
}
]

我想通过在父级中引入子级数组来将上面的数组转换如下

let subCredit = [
{
   creditNr : "A001"
   creditUsage:[
   {
     id: 1,
     parentId :null
     children:[
       {id: 11,
        parentId :1}
       ]
   },
   {
     id: 2,
     parentId :null
     children:[
       {id: 22,
        parentId :2}
       ]
    }
   ]
},
]

我正在过滤所有 rootCredits 并首先存储它,然后尝试向其中添加子节点,但无法实现

export const displayCredit(subCredits)=>
{

let root = filterRootCredits(subCredits);
let usage=[];
 const treeData = root.map(r=>{
   subCredits.map(s=>{
   usage = r.creditUsage.map(node => {
   const children =s.creditUsages.filter(item=>item.parentId ===node.id).map(item =>{return item;})
return {

...node,
children
}
})
})
return subCredit;
})
 
return treeData;
}

1 个答案:

答案 0 :(得分:0)

这可以通过递归函数轻松解决(类似于reduce,带有累加器)。

这是一个非常匆忙的草稿:

function nest_them(creds, acc) {
    if (creds.length == 0) {
      return acc
    }
    var [c, ...rest] = creds
    if (c.parentId) {
      let parent = acc.find(x => x.id == c.parentId);
      (parent.children = parent.children || []).push(c)
      return nest_them(rest, acc)
    } else {
      return nest_them(rest, [...acc, c])
    }
}

你可以这样使用:

subCredits.map(x => ({...x, creditUsage: nest_them(x.creditUsage, [])}))