【发布时间】:2021-02-16 17:15:24
【问题描述】:
我正在尝试将一个对象数组(数组中的每个对象都有一个路径和 id)转换为代表该路径的树。例如,对于[{path: 'foo/bar/baz', id: 1}]的给定输入,输出如下所示
[
{
"path": "foo",
"children": [
{
"path": "bar",
"children": [
{
"path": "baz",
"children": [],
}
]
}
]
}
]
到目前为止,我有以下代码:
const pathObjs = [
{ id: 1, path: 'foo/bar/baz' },
];
const result = [];
const level = { result };
for (p of pathObjs) {
p.path.split('/').reduce((r, path) => {
if (!r[path]) {
r[path] = { result: [] };
const p = { path, children: r[path].result };
r.result.push(p);
}
return r[path];
}, level);
}
我不知道如何在正确的级别分配每个路径的id,以便最终结果如下所示:
[
{
"path": "foo",
"children": [
{
"path": "bar",
"children": [
{
"path": "baz",
"children": [],
// how to add this guy here!
"id": 1,
}
]
}
]
}
]
请有人将我推向正确的方向。
【问题讨论】:
标签: javascript algorithm tree