图一:原数据,图二:期望得到的树形数据
toTree(data) {//-data为原数据数组
let result = [];
if (!Array.isArray(data)) {
return result;
}
data.forEach((item) => {
delete item.children;
});
let map = {};
data.forEach((item) => {
map[item.id] = item;
});
data.forEach((item) => {
let parent = map[item.parentid];
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
result.push(item);
}
});
// console.log(12,result)//最新数据
this.result = result;
return result;
},