Javascript 如何编辑树结构?
树结构看起来像这样-Javascript 如何编辑树结构?,javascript,arrays,recursion,ecmascript-6,functional-programming,Javascript,Arrays,Recursion,Ecmascript 6,Functional Programming,树结构看起来像这样- const init = [ { name: 'A', children: [ { name: 'A1', children: [] }, { name: 'A2', children: [ {
const init = [
{
name: 'A',
children: [
{
name: 'A1',
children: []
},
{
name: 'A2',
children: [
{
name: 'A21',
children: []
}
]
}
]
},
{
name: 'B',
children: [
{
name: 'B1',
children: []
},
{
name: 'B2',
children: []
}
]
}
]
我有变量
currentPath=['A','A2','A21']
node={name:'A211',子项:[]}
const init = [
{
name: 'A',
children: [
{
name: 'A1',
children: []
},
{
name: 'A2',
children: [
{
name: 'A21',
children: [
{
name: 'A211',
children: []
}
]
}
]
}
]
},
{
name: 'B',
children: [
{
name: 'B1',
children: []
},
{
name: 'B2',
children: []
}
]
}
]
请告诉我需要使用的函数是什么funcAppendNode(init,currentPath,node)
,它接受init、currentPath和新节点并返回新的init。我认为这与递归有关,但我无法成功
这是我到目前为止所做的尝试
const funcAppend = (init, currentPath, node) => {
let newState = [...init]
for (let i = 1; i < currentPath.length; i++) {
newState = newState.find(o => o.name === currentPath[i]).children
}
newState.push(node)
return newState
}
constfuncappend=(init,currentPath,node)=>{
让newState=[…init]
for(设i=1;io.name==currentPath[i]).children
}
newState.push(节点)
返回新闻状态
}
上述函数正在返回
[{name:'A211',children:[]}]
请帮忙。
const init=[
{
名称:‘A’,
儿童:[
{
名称:“A1”,
儿童:[]
},
{
名称:“A2”,
儿童:[
{
名称:“A21”,
儿童:[]
}
]
}
]
},
{
名称:‘B’,
儿童:[
{
名称:‘B1’,
儿童:[]
},
{
名称:“B2”,
儿童:[]
}
]
}
];
常数currentPath=['A','A2','A21'];
常量节点={name:'A211',子节点:[]};
让target={children:init};
currentPath.forEach(路径=>{
target=target.children.find(child=>child.name==path);
});
target.children.push(节点);
console.log(init)代码>
。作为控制台包装{top:0;最大高度:100%!important;}
我同意递归。。。所以首先,你要寻找退出条件。。。这是path.length=1
。你知道在这种情况下该怎么办
如果不满足退出条件,则应调用传递一组新参数的函数“reduced”
与您的示例类似,我决定将节点添加到items中的所有路径(而不仅仅是第一个路径)
我会这样处理这个问题:
从名称数组
,构建树路径
在树路径上,只需附加新节点
const toTreePath=([head,…tail],data)=>{
const index=data.findIndex((node)=>node.name==head);
const next=数据[索引]?.子项;
return[索引'children'].concat(
下一个?长度?总路径(尾部,下一个):[]
);
};
const append=(节点、路径、数据)=>{
const$path=toTreePath(路径,数据);
返回右上角(
R.lensPath($path),
R.append(节点),
数据,
);
}
// ======
const newNode='HELLO WORLD';
常量路径=['A','A2','A21'];
常数数据=[
{
名称:‘A’,
儿童:[
{
名称:“A1”,
儿童:[]
},
{
名称:“A2”,
儿童:[
{
名称:“A21”,
儿童:[]
}
]
}
]
},
{
名称:‘B’,
儿童:[
{
名称:‘B1’,
儿童:[]
},
{
名称:“B2”,
儿童:[]
}
]
}
];
console.log(
追加(新节点、路径、数据),
);代码>
您能否添加一个描述,说明您为实现此目的所做的工作?很明显,您迭代地遍历了范围并更新了目标,但是一个TL;博士至少会帮忙的。
appendNode(items, path, node) {
if (path.length === 1) {
for (item in items.filter(item => item.name = path[0])) {
item.children.push(node)
}
} else {
const firstElement = path.shift(); //removed the first element from path
for (item in items.filter(item => item.name = firstElement)) {
addNode(item.children, path, node)
}
}
}