直接上代码
mock数据
// 创建一个乱序数组
const ids = [
{
id: 1,
name: "1",
pid: 0
},
{
id: 11,
name: "1-1",
pid: 1
},
{
id: 111,
name: "1-1-1",
pid: 11
},
{
id: 2,
name: "2",
pid: 0
},
{
id: 22,
name: "2-2",
pid: 2
},
].sort(() => Math.random() < 0.5)
数组转树代码
const arrToTree = (arr) => {
const idMap = {},treeArr = [];
arr.forEach((item) => {
idMap[item.id] ? item.children = idMap[item.id] : (idMap[item.id] = [], item.children = idMap[item.id])
if (item.pid === 0) return treeArr.push(item)
idMap[item.pid] ? idMap[item.pid].push(item) : idMap[item.pid] = [item]
});
return treeArr
}
const result = arrToTree(ids)
console.log(result)
利用了js中引用值的特性,先创建了一个map pid作为key value 是具有相同pid的元素 如果我这个id 有在 map 里面找到 那么这些就都是我的 children 否则创建一个[] 并等待我的子元素往里面push