按级别对 JavaScript 数组进行排序
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 18:20:17
我们在同一个数组中拥有具有一对多关系的数据。组织按级别建立。元素的父元素始终比其自身高一个级别,并由 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
}
]
}
]
}
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

