JS 将json数组转为嵌套层级数组

时间:2022-07-08 05:14:17

ele UI 的树级菜单的数据要求是这种嵌套的,但是Ztree的老用发的是

JS 将json数组转为嵌套层级数组

var zNodes =[
{ id:, pId:, name:"zTree Home", pid:0},
{ id:, pId:, name:"zTree in Google",pid:0},
       { id:, pId:, name:"zTree in Iteye",pid:1}]

这种以pid来识别父级关系的,话不多说转换

  //将数组转成嵌套的
buildTree (arr) {
let temp = {}
let tree = {}
// 数组转 键值对
arr.forEach(item => {
temp[item.id] = item
}) let tempKeys = Object.keys(temp)
tempKeys.forEach(key => {
// 获取当前项
let item = temp[key]
// 当前项 pId
let _itemPId = item.pid
// 获取父级项
let parentItemByPid = temp[_itemPId]
if (parentItemByPid) {
if (!parentItemByPid.children) {
parentItemByPid.children = []
}
parentItemByPid.children.push(item)
} else {
tree[item.id] = item
}
})
// 对象转数组并返回
return Object.keys(tree).map(key => tree[key])
},

!!!