我们常常在做后台管理系统的时候 需要对数据进行组装成一个树装结构,这里特地将此方法进行封装:

let data = [
{ id: , text: 't11', parentId: },
{ id: , text: 't11', parentId: },
{ id: , text: 't11', parentId: },
{ id: , text: 't11', parentId: },
{ id: , text: 't11', parentId: },
{ id: , text: 't11', parentId: }
]
function treeData (data, id, parentId, childName) {
let cloneData = JSON.parse(JSON.stringify(data))
return cloneData.filter((father) => {
let newArr = cloneData.filter((child) => {
return father[id] === child[parentId]
})
father[childName] = newArr
return father[parentId] ===
})
}
let msg = treeData(data, 'id', 'parentId', 'childaaa')
console.log(msg)
05-25 11:44