[英]javascript replace property name in n-ary tree object
假設我有一個像這樣的 n 元樹結構(在 json 中):
[
{
"text": "Some title",
"children": [
{
"text": "Some title",
"children": [
...
]
},
...
]
}
]
我既不知道節點將有多少個孩子,也不知道樹的深度。
我想這樣做的是改變屬性的名稱text
來name
,所有的孩子。
我已經嘗試過這個,使用遞歸函數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%;}
您將在此處使用 in 運算符。
for (let node **in** tree) {
node.name = node.text
delete node.text;
return func(node.children);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.