我们在同一数组中具有一对多关系的数据。该组织是按级别建立的。元素的父级始终比其自身高一级,并由parentId引用。
我们需要从该数组获取多级数组。具有最高级别的元素将是主数组,其子元素为子数组。
如果输入数组由-给定
const arr = [ { _id: 100, level: 3, parentId: null, }, { _id: 101, level: 2, parentId: 100, }, { _id: 102, level: 2, parentId: 100, }, { _id: 103, level: 2, parentId: 100, }, { _id: 104, level: 1, parentId: 101, }, { _id: 105, level: 1, parentId: 102, }, { _id: 106, level: 1, parentId: 101, }, { _id: 107, level: 1, parentId: 103, }, { _id: 108, level: 1, parentId: 102, }, { _id: 109, level: 1, parentId: 103, } ];
然后,输出结构应类似于-
100 | ------------------------------------ | | | 101 102 103 ------- ------ ------ | | | | | | 104 106 105 108 107 109
为此的代码将是-
const arr = [{ _id: 100, level: 3, parentId: null, }, { _id: 101, level: 2, parentId: 100, }, { _id: 102, level: 2, parentId: 100, }, { _id: 103, level: 2, parentId: 100, }, { _id: 104, level: 1, parentId: 101, }, { _id: 105, level: 1, parentId: 102, }, { _id: 106, level: 1, parentId: 101, }, { _id: 107, level: 1, parentId: 103, }, { _id: 108, level: 1, parentId: 102, }, { _id: 109, level: 1, parentId: 103, }]; const prepareTree = (arr = [], root = null) => { let res; const obj = Object.create(null); arr.forEach(el => { el.children = obj[el._id] && obj[el._id].children; obj[el._id] = el; if (el.parentId === root) { res = el; } else { obj[el.parentId] = obj[el.parentId] || {}; obj[el.parentId].children = obj[el.parentId].children || []; obj[el.parentId].children.push(el); } }); return res; }; console.log(JSON.stringify(prepareTree(arr), undefined, 4));
输出结果
控制台中的输出将是-
{ "_id": 100, "level": 3, "parentId": null, "children": [ { "_id": 101, "level": 2, "parentId": 100, "children": [ { "_id": 104, "level": 1, "parentId": 101 }, { "_id": 106, "level": 1, "parentId": 101 } ] }, { "_id": 102, "level": 2, "parentId": 100, "children": [ { "_id": 105, "level": 1, "parentId": 102 }, { "_id": 108, "level": 1, "parentId": 102 } ] }, { "_id": 103, "level": 2, "parentId": 100, "children": [ { "_id": 107, "level": 1, "parentId": 103 }, { "_id": 109, "level": 1, "parentId": 103 } ] } ] }