我正在尝试将一个对象数组(数组中的每个对象都有一个路径和 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,
}
]
}
]
}
]
有人可以将我推向正确的方向吗?
MM们
长风秋雁
相关分类