假设我有一个像这样的 n 元树结构(以 json 形式):
[
{
"text": "Some title",
"children": [
{
"text": "Some title",
"children": [
...
]
},
...
]
}
]
Run Code Online (Sandbox Code Playgroud)
我既不知道节点将有多少个子节点,也不知道树的深度。
我想做的是将所有孩子的财产名称更改text为。name
我已经尝试过这个,使用递归函数func:
func(tree) {
if (!tree) return;
for (let node of tree) {
node.name = node.text
delete node.text;
return func(node.children);
}
}
Run Code Online (Sandbox Code Playgroud)
但这没有用。我该怎么做呢?
我想说,您的代码的主要问题是node变量保存相应数组项的值,并且它不保留对这些项本身的引用,因此,基本上,您尝试进行的突变永远不会应用于原始数组(但是仅适用于每次循环迭代时重新分配的临时变量)
如果您更喜欢改变原始数组并且愿意使用for(-loops 来实现此目的,那么最好使用for(..in-loop 通过键访问数组项:
const src = [
{
text: "Some title",
children: [
{
text: "Some title",
children: []
},
]
}
],
func = tree => {
for(const nodeIdx in tree){
const {text:name, children} = tree[nodeIdx]
func(children)
tree[nodeIdx] = {name, children}
}
}
func(src)
console.log(src)Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper{min-height:100%;}Run Code Online (Sandbox Code Playgroud)
但是,我会避免改变源数据并返回新数组(例如使用Array.prototype.map():
const src = [
{
text: "Some title",
children: [
{
text: "Some title",
children: []
},
]
}
],
func = tree =>
tree.map(({text:name,children}) => ({
name,
...(children && {children: func(children)})
}))
console.log(func(src))Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper{min-height:100%;}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
713 次 |
| 最近记录: |