从 JSON 中在 JavaScript 中构建树形数组
假设在 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" } ] } ] } ]
广告