JS基石之-----数组转换为树结构函数
我们常常在做后台管理系统的时候 需要对数据进行组装成一个树装结构,这里特地将此方法进行封装:
let data = [ { id: 1, text: 't11', parentId: 0 }, { id: 2, text: 't11', parentId: 0 }, { id: 3, text: 't11', parentId: 1 }, { id: 4, text: 't11', parentId: 1 }, { id: 5, text: 't11', parentId: 3 }, { id: 6, text: 't11', parentId: 2 } ] 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] === 0 }) } let msg = treeData(data, 'id', 'parentId', 'childaaa') console.log(msg)