js 写一个数组转树形结构的函数
时间: 2024-06-01 09:09:47 浏览: 43
js代码-数组根据pid转为树形结构的数组
function arrayToTree(arr) {
let map = {}, node, roots = [], i;
for (i = 0; i < arr.length; i += 1) {
map[arr[i].id] = i;
arr[i].children = [];
}
for (i = 0; i < arr.length; i += 1) {
node = arr[i];
if (node.parentId !== "0") {
arr[map[node.parentId]].children.push(node);
} else {
roots.push(node);
}
}
return roots;
}
// 示例
let arr = [
{id: "1", name: "节点1", parentId: "0"},
{id: "2", name: "节点2", parentId: "1"},
{id: "3", name: "节点3", parentId: "1"},
{id: "4", name: "节点4", parentId: "2"},
{id: "5", name: "节点5", parentId: "2"},
{id: "6", name: "节点6", parentId: "3"},
{id: "7", name: "节点7", parentId: "3"},
];
let tree = arrayToTree(arr);
console.log(tree);
/*
[
{
"id": "1",
"name": "节点1",
"parentId": "0",
"children": [
{
"id": "2",
"name": "节点2",
"parentId": "1",
"children": [
{
"id": "4",
"name": "节点4",
"parentId": "2",
"children": []
},
{
"id": "5",
"name": "节点5",
"parentId": "2",
"children": []
}
]
},
{
"id": "3",
"name": "节点3",
"parentId": "1",
"children": [
{
"id": "6",
"name": "节点6",
"parentId": "3",
"children": []
},
{
"id": "7",
"name": "节点7",
"parentId": "3",
"children": []
}
]
}
]
}
]
*/
阅读全文