我们有一个复杂的json文件,必须使用JavaScript处理才能使其具有层次结构,以便稍后构建树。
JSON数组的每个条目都有-
id-唯一的ID,
parentId-父节点的ID(如果节点是树的根,则为0)
级别-树中的深度级别
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": [] } ] } ]