【发布时间】:2023-03-21 00:25:01
【问题描述】:
我有以下平面数据数组,主要是级别,并且是有序的。根据层次,我需要创建一个树层次数组。
以下是输入:
[
{
"position": "CEO",
"level": 1,
"name": "Adam"
},
{
"position": "President",
"level": 2,
"name": "Eva"
},
{
"position": "Senior Vice President",
"level": 3,
"name": "Thein"
},
{
"position": "Vice President",
"level": 4,
"name": "Rick"
},
{
"position": "Vice President",
"level": 4,
"name": "Rosh"
},
{
"position": "Vice President",
"level": 4,
"name": "Jenny"
},
{
"position": "Vice President",
"level": 4,
"name": "Tim"
},
{
"position": "Vice President",
"level": 4,
"name": "Gin"
},
{
"position": "President",
"level": 2,
"name": "Nisham"
},
{
"position": "Senior Vice President",
"level": 3,
"name": "Gil"
},
{
"position": "Vice President",
"level": 4,
"name": "Lew"
},
{
"position": "Vice President",
"level": 4,
"name": "Dan"
},
{
"position": "Vice President",
"level": 4,
"name": "Henry"
}
]
预期的输出是:
[
{
"position": "CEO",
"level": 1,
"name": "Adam",
"children": [
{
"position": "President",
"level": 2,
"name": "Eva",
"children": [
{
"position": "Senior Vice President",
"level": 3,
"name": "Thein",
"children":[
{
"position": "Vice President",
"level": 4,
"name": "Rick"
},
{
"position": "Vice President",
"level": 4,
"name": "Rosh"
},
{
"position": "Vice President",
"level": 4,
"name": "Jenny"
},
{
"position": "Vice President",
"level": 4,
"name": "Tim"
},
{
"position": "Vice President",
"level": 4,
"name": "Gin"
}
]
}
]
},
{
"position": "President",
"level": 2,
"name": "Nisham",
"children":[
{
"position": "Senior Vice President",
"level": 3,
"name": "Gil",
"children":[
{
"position": "Vice President",
"level": 4,
"name": "Lew"
},
{
"position": "Vice President",
"level": 4,
"name": "Dan"
},
{
"position": "Vice President",
"level": 4,
"name": "Henry"
}
]
}
]
}
]
}
]
我遇到了很多堆栈,但它们都有一个 id 和 parent_id 作为链接。但是,在这个数据中,数组项之间没有id链接。
到目前为止,我尝试了以下代码:
let root = {};
let i = 0;
data.forEach(el => {
if (el["level"] == 1) {
root = el;
root.children = [];
}
if (el["level"] == 2) {
root.children.push(el);
root.children[i].children = [];
}
if (el["level"] == 3) {
root.children[i].children.push(el);
root.children[i].children[i].children = [];
}
if (el["level"] == 4) {
root.children[i].children[i].children.push(el);
root.children[i].children[i].children[i].children = [];
}
i++;
});
它为第一遍提供输出,但稍后会抛出错误。我知道这是不对的,而且关卡是硬编码的,但到目前为止,这就是尝试。
【问题讨论】:
-
请考虑,仅仅因为您可能有 5 个(或任意数量)
root.children[],并不意味着您将始终拥有 5 个root.children[].children[]。您对i的使用范围太广。
标签: javascript arrays tree hierarchy