[
{
"id": 1,
"name": "node1",
"children": [
{
"id": 11,
"name": "node1.1",
"children": [
{
"id": 111,
"name": "node1.1.1",
"children": [
{
"id": 1111,
"name": "node1.1.1.1",
"children": []
}
]
}
]
},
{
"id": 12,
"name": "node1.2",
"children": []
}
]
}
]
function buildTree(list) {
const map = {};
return list
.sort((a, b) => Number(a.pid) - Number(b.pid))
.reduce((tree, category) => {
if (!map[category.id]) {
map[category.id] = {
id: category.id
children: []
};
}
if (category.pid) {
map[category.pid].children.push(map[category.id]);
} else {
tree.push(map[category.id]);
}
return tree;
}, []);
}
Find more questions by tags JavaScript
How do I add children to the second element? - geoffrey_Ste commented on July 8th 19 at 16:15