记录一下:
假设原始数据如下
let data = [
{
"id": "1",
"name": "1",
"fatherId": "0",
},
{
"id": "2",
"name": "1-1",
"fatherId": "1"
},
{
"id": "3",
"name": "1-2",
"fatherId": "1"
},
{
"id": "4",
"name": "1-1-1",
"fatherId": "2"
},
{
"id": "5",
"name": "1-1-2",
"fatherId": "2"
},
{
"id": "6",
"name": "2",
"fatherId": "0"
},
{
"id": "7",
"name": "1-2-1",
"fatherId": "3"
}
];
使用map处理数据
const map = {};
const val = [];
data.forEach((item) => {
map[item.id] = item;
});
data.forEach((item) => {
const parent = map[item.fatherId];
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
val.push(item);
}
});
你就是这个
过来学习一下!