Javascript 从平面阵列构建层次结构,同时从不需要的节点升级子节点
具有创建层次结构的功能,但需要一种高效的方法来构建层次结构,同时删除不需要的节点并将其子节点提升为有效的父节点 注意:父节点将始终显示在数组中的子节点之前Javascript 从平面阵列构建层次结构,同时从不需要的节点升级子节点,javascript,typescript,ecmascript-6,Javascript,Typescript,Ecmascript 6,具有创建层次结构的功能,但需要一种高效的方法来构建层次结构,同时删除不需要的节点并将其子节点提升为有效的父节点 注意:父节点将始终显示在数组中的子节点之前 Node { id: string, parentNodeId: string, flag: boolean, children: Node[] }; function buildTree(nodes) { var tree; var childrenOf = new Map(); nodes.forEach(
Node { id: string, parentNodeId: string, flag: boolean, children: Node[] };
function buildTree(nodes) {
var tree;
var childrenOf = new Map();
nodes.forEach(node => {
if (!childrenOf.has(node.id)) {
childrenOf.set(node.id, []);
}
node.childNodes = childrenOf.get(node.id);
if (node.parentId != null) {
childrenOf.has(node.parentId) ?
childrenOf.get(node.parentId).push(node) : childrenOf.set(node.parentId, [node]);
} else {
tree = node;
}
});
return tree;
}
Remove nodes当标志为true时,在JSFIDLE json中,需要删除node.id 1和2,同时将3作为子节点升级到节点0。当标志为true时,上述函数不会删除,它只是构建层次结构
小提琴中示例的预期输出:
{
"id":"0",
"parentId":null,
"children":null,
"flag":"false",
"childNodes":[
{
"id":"3",
"parentId":"2",
"children":null,
"flag":"false",
"childNodes":[
{
"id":"4",
"parentId":"3",
"children":null,
"flag":"false",
"childNodes":[
]
},
{
"id":"5",
"parentId":"3",
"children":null,
"flag":"false",
"childNodes":[
]
}
]
},
{
"id":"6",
"parentId":"0",
"children":null,
"flag":"false",
"childNodes":[
]
}
]
}
下面是基于递归调用的javascript方法(无限深度的“家长化”),它可以很容易地应用于typescript项目:
const buildTreeHierarchy = (nodes, perentId) => {
const result = nodes
.filter(n => n.parentId === perentId && n.flag !== 'true')
.map(n => ({...n, children: buildTreeHierarchy(nodes, n.id)}));
return result.length ? result : null;
}
buildTreeHierarchy(example, null);
示例
参数是您的初始JSON数组。帮助我们帮助您。告诉我们你得到了什么不良结果。此外,定义“高效”。不希望出现的结果:即使标志为true,节点也会出现。高效:O(n)没有递归?你害怕递归吗?;)您的数据可能有多少个级别?不必担心,但要寻找优雅的迭代解决方案,毫无疑问,这是一个很好的递归解决方案。如果您有两个以上的级别,非递归解决方案也不会优雅。它将有两个以上的级别,但需要注意的是,父级将始终出现在数组中的子级之前。