gpt4 book ai didi

javascript替换n元树对象中的属性名称

转载 作者:行者123 更新时间:2023-12-01 15:39:41 25 4
gpt4 key购买 nike

假设我有一个像这样的 n 元树结构(在 json 中):

[
{
"text": "Some title",
"children": [
{
"text": "Some title",
"children": [
...
]
},
...
]
}
]
我既不知道节点将有多少 child 也不知道树的深度。
我想做的是更改属性名称 textname ,在所有 child 身上。
我已经尝试过了,使用递归函数 func :
func(tree) {
if (!tree) return;

for (let node of tree) {
node.name = node.text
delete node.text;

return func(node.children);
}
}
但它没有用。我该怎么做?

最佳答案

我想说,您的代码的主要问题是 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)
.as-console-wrapper{min-height:100%;}

但是,我会避免改变源数据并返回新数组(例如使用 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))
.as-console-wrapper{min-height:100%;}

关于javascript替换n元树对象中的属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63837761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com