- 方法一:
arrayToTree(data, pid) {
const result = [];
this.getChildren(data, result, pid);
return result;
},
getChildren(data, result, pid) {
data.forEach((item, index) => {
if (item.pid === pid) {
const newItem = { ...item, children: [] };
result.push(newItem);
// ++index 不考虑id,单纯的分层
this.getChildren(data, newItem.children, ++index);
// item.id 需要pid和id是有关联关系的
//this.getChildren(data, newItem.children, item.id);
}
});
},
- 方法二:
arrayToTree3(arr) {
return arr.map((item) => {
item.children = arr.filter((val) => val.pid === item.id);
return item;
})[0];
},
文章介绍了两种在JavaScript中将数组转换为树形结构的方法。方法一是通过递归遍历数据,根据pid构建树;方法二是使用map和filter函数,根据id匹配子项。这两种方法都用于处理层级关系的数据。
1404

被折叠的 条评论
为什么被折叠?



