使用 JavaScript 从 JSON 构建树形数组
javascriptweb developmentfront end technologyobject oriented programmingjson
假设,我们在 JavaScript 中有以下数组 −
const arr = [{ "code": "2", "name": "PENDING" }, { "code": "2.2", "name": "PENDING CHILDREN" }, { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }, { "code": "1", "name": "ACTIVE" }, { "code": "1.1", "name": "ACTIVE CHILDREN" }, { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }];
我们需要编写一个 JavaScript 函数来接收一个这样的数组。该函数应根据对象的"name"属性从该数组构建一个树结构。
因此,对于上述数组,输出应如下所示 −
const output = [{ "code": "2", "name": "PENDING", "children": [{ "code": "2.2", "name": "PENDING CHILDREN", "children": [{ "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }] }] }, { "code": "1", "name": "ACTIVE", "children": [{ "code": "1.1", "name": "ACTIVE CHILDREN", "children": [{ "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }] }] }];
示例
其代码为 −
const arr = [{ "code": "2", "name": "PENDING" }, { "code": "2.2", "name": "PENDING CHILDREN" }, { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }, { "code": "1", "name": "ACTIVE" }, { "code": "1.1", "name": "ACTIVE CHILDREN" }, { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }]; const transformToTree = (arr, root = '') => { let map = {}, last = [root], level = 0; map[root] = {}; arr.forEach(el => { let parent = root; while (level && last[level].length >= el.code.length) { level--; }; parent = last[level]; level++; last.length = level; last.push(el.code); map[el.code] = el; map[parent].children = map[parent].children || []; map[parent].children.push(el); }); return map[root].children; }; console.log(JSON.stringify(transformToTree(arr), undefined, 4));
输出
控制台中的输出将是 −
[ { "code": "2", "name": "PENDING", "children": [ { "code": "2.2", "name": "PENDING CHILDREN", "children": [ { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" } ] } ] }, { "code": "1", "name": "ACTIVE", "children": [ { "code": "1.1", "name": "ACTIVE CHILDREN", "children": [ { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" } ] } ] } ]