关于javascript:用js将平数组转成keyvalue值再转成有上下级的结构数据

42次阅读

共计 868 个字符,预计需要花费 3 分钟才能阅读完成。

有一组 js 数组:

let data=[{id:1,parentid:0,name:'春树团体'},
    {id:2,parentid:0,name:'海亮团体'},
    {id:3,parentid:1,name:'科技部'},
    {id:4,parentid:1,name:'设计部'},
    {id:5,parentid:1,name:'运维部'},
    {id:6,parentid:2,name:'科技部'},
    {id:7,parentid:2,name:'客服部'},
]

应用如下代码:

let dataMap={}
data.map(item=>{dataMap[item.id]=item
})

就失去了上面的对象:

{'1': { id: 1, parentid: 0, name: '春树团体'},
  '2': {id: 2, parentid: 0, name: '海亮团体'},
  '3': {id: 3, parentid: 1, name: '科技部'},
  '4': {id: 4, parentid: 1, name: '设计部'},
  '5': {id: 5, parentid: 1, name: '运维部'},
  '6': {id: 6, parentid: 2, name: '科技部'},
  '7': {id: 7, parentid: 2, name: '客服部'}
}

而后再:

const rootList=[]
data.map(item=>{if(!item.parentid){rootList.push(item)
    }else{if(dataMap[item.parentid].children===undefined){dataMap[item.parentid].children=[]}
        dataMap[item.parentid].children.push(item);
    }
})

就变成了:

[
  {
    id: 1,
    parentid: 0,
    name: '春树团体',
    children: [[Object], [Object], [Object] ]
  },
  {
    id: 2,
    parentid: 0,
    name: '海亮团体',
    children: [[Object], [Object] ]
  }
]

正文完
 0