我正在尝试递归地创建一个嵌套对象。下面是示例数据:
"reactions": [
{
"name": "Ester amidation",
"target": "Data #1",
"sources": ["Data #2", "Data #3"],
},
{
"name": "Buchwald-Hartwig amination with amide",
"target": "Data #4",
"sources": ["Data #5", "Data #1"], // BECAUSE Data #1 is a target AND in sources for Data #4, we should nest it as a child of Data #4
}
]
对于target
,我试图得到一个输出如下的东西:
{
name: "My Route 1",
children: [
{
name: "Data #4",
children: [
{
name: "Data #5",
children: []
},
{
name: "Data #1",
children: [
{
name: "Data #2",
children: []
},
{
name: "Data #3",
children: []
}
]
},
],
},
],
};
我尝试过类似这样的方法,但在处理数组时我感到困惑:
function createNestedTree(objects, target = null) {
const children = objects.filter(o => o.target === target);
if (!children.length) {
return null;
}
return children.map(child => ({
...child,
children: createNestedTree(objects, child.id)
}));
}
有人知道如何创建一个算法吗?非常感谢!
1条答案
按热度按时间wlzqhblo1#
你可以先迭代数据来创建目标对象(用空的
children
数组),然后在一个以名称为键的Map中引用它们,然后迭代数据来填充那些children
数组,同时将子对象标记为不是根,返回剩下的根。下面是一个可能的实现: