在 JavaScript 中利用平面数组构建树数组
我们有一个复杂的 JSON 文件,我们必须使用 JavaScript 处理它以使其具有层次结构,以便稍后构建树。
JSON 数组的每个条目都有 −
id − 唯一的 ID,
parentId − 父节点的 ID(如果节点是树的根,则为 0)
level − 树中的深度级别
JSON 数据已经被“排序”,这意味着一个条目其上将有一个父节点或兄弟节点,其下将有一个子节点或兄弟节点。
输入数组为 −
const arr = [ { "id": "12", "parentId": "0", "text": "Man", "level": "1", "children": null }, { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": null }, { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": null }, { "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children": null }, { "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children": null } ];
预期输出为 −
const output = [ { "id": "12", "parentId": "0", "text": "Man", "level": "1", "children": [ { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": [] }, { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": [] } ] }, { "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children": [ { "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children": [] } ] } ];
示例
此代码为 −
const arr = [ { "id": "12", "parentId": "0", "text": "Man", "level": "1", "children": null }, { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": null }, { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": null }, { "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children": null }, { "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children": null } ]; const listToTree = (arr = []) => { let map = {}, node, res = [], 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 { res.push(node); }; }; return res; }; console.log(JSON.stringify(listToTree(arr), undefined, 4));
输出
控制台中的输出为 −
[ { "id": "12", "parentId": "0", "text": "Man", "level": "1", "children": [ { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": [] }, { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": [] } ] }, { "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children": [ { "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children": [] } ] } ]
广告