- 方法一:
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];
},