前几天同学写了一个非常简单的组装树结构,让我惊掉了下巴,于是记录一下
组装只有一个顶级的树结构
var aTree = [
{ "id": "1", "name": "动物", "pid": "0"},
{ "id": "2", "name": "鸟类", "pid": "3"},
{ "id": "3", "name": "无脊椎动物", "pid": "4"},
{ "id": "4", "name": "哺乳动物", "pid": "1"}
];
let obj = {}
aTree.forEach(item => {
if (item.pid === '0') {obj = item}
item.childArr = aTree.filter(items => items.pid === item.id)
})
console.log(obj)
打印结果如下
{
"id": "1", "name": "动物", "pid": "0", childArr: [
{
"id": "4", "name": "哺乳动物", "pid": "1", childArr: [
{
"id": "3", "name": "无脊椎动物", "pid": "4", childArr: [
{ "id": "2", "name": "鸟类", "pid": "3", childArr: [] },
]
},
]
}
]
}
那么我们来捋以下实现过程
1.定义一个对象如果pid为0的话那么就是顶级,直接让空对象obj接收顶级对象,这里obj和aTree[0]共用一个引用空间地址
2.item.childArr = aTree.filter(items => items.pid === item.id)
这行代码是过滤出对应的子集,让我们看看过滤过程,item.childArr是为item增加一个childArr属性
1 当item为
{ "id": "1", "name": "动物", "pid": "0"}
时,会找到pid为1的对象然后filter返回的是一个数组
{
"id": "1", "name": "动物", "pid": "0", childArr: [
{ "id": "4", "name": "哺乳动物", "pid": "1",childArr:[]
}
]
}
2 当item为
{ "id": "2", "name": "鸟类", "pid": "3" }
时,并没有找到pid为2的,所以返回一个空数组
{ "id": "2", "name": "鸟类", "pid": "3",childArr:[]}
3 当item为
{ "id": "3", "name": "无脊椎动物", "pid": "4" }
时,会找到id为2的对象
{
"id": "3", "name": "无脊椎动物", "pid": "4", childArr: [
{ "id": "2", "name": "鸟类", "pid": "3", childArr: [] }
]
}
4 当item为
{ "id": "4", "name": "哺乳动物", "pid": "1" }
时找到了id为3的数组
{
"id": "4", "name": "哺乳动物", "pid": "1", childArr: [
{
"id": "3", "name": "无脊椎动物", "pid": "4", childArr: [
{ "id": "2", "name": "鸟类", "pid": "3", childArr: [] },
]
}
]
}
那么有人问了为什么pid为0的下面只有一个ID为4的,为什么打印出来的却是正确的我们想要的结果,这个问题纠结我半小时,然后同学跟我讲解了一下才豁然开朗,因为pid为0的childArr中的对象与id为4的对象共用了一个空间地址或者说他们两个就是一个东西,所以打印aTree的索引为3的如下
{
"id": "4", "name": "哺乳动物", "pid": "1", childArr: [
{
"id": "3", "name": "无脊椎动物", "pid": "4", childArr: [
{ "id": "2", "name": "鸟类", "pid": "3", childArr: [] },
]
}
]
}
组装多级的树结构
var aTree = [
{ "id": "1", "name": "动物", "pid": "0" },
{ "id": "2", "name": "鸟类", "pid": "0" },
{ "id": "3", "name": "无脊椎动物", "pid": "4" },
{ "id": "4", "name": "哺乳动物", "pid": "1" }
];
let arr = []
aTree.forEach(item => {
if (item.pid === '0') { arr.push(item) }
item.childArr = aTree.filter(items => items.pid === item.id)
})
console.log(arr)