gpt4 book ai didi

Javascript通过数组路径更新嵌套对象中的值

转载 作者:行者123 更新时间:2023-11-30 14:16:29 24 4
gpt4 key购买 nike

给定嵌套对象:

{
name: 'UK',
toggled: false,
active: false,
children: [{
name: 'Region 1',
active: false,
toggled: false,
children: [{
name: 'Heathrow T1',
toggled: false,
active: false,
children: []
},
{
name: 'HTT',
toggled: false,
active: false,
children: []
},
]
},
{
name: 'Region 2',
active: false,
toggled: false,
children: [{
name: Gatwick North,
active: false,
toggled: false,
children: []
}]
}
]
}

和给定的路径

['UK', 'Region 2', 'Gatwick North']

我如何设法为与上述数组匹配的嵌套对象中的路径将事件/切换属性添加为 true。

输出应该是这样的:

{
name: 'UK',
toggled: true,
active: true,
children: [{
name: 'Region 1',
active: false,
toggled: false,
children: [{
name: 'Heathrow T1',
toggled: false,
active: false,
children: []
},
{
name: 'HTT',
toggled: false,
active: false,
children: []
},
]
},
{
name: 'Region 2',
active: true,
toggled: true,
children: [{
name: 'Gatwick North',
active: true,
toggled: true,
children: []
}]
}
]
}

我试图用递归来实现它,但到目前为止没有成功。我正在搜索问题,但没有一个符合我目前的情况。

最佳答案

使用递归的简单示例,解释在代码中作为注释

const obj = {name: 'UK',toggled: false,active: false,children: [{name: 'Region 1',active: false,toggled: false,children: [{name: 'Heathrow T1',toggled: false,active: false,children: []},{name: 'HTT',toggled: false,active: false,children: []},]},{name: 'Region 2',active: false,toggled: false,children: [{name: 'Gatwick North',active: false,toggled: false,children: []}]}]};

const checkAndChange = (obj) => { // function that will check if name exists in array and change toggle and active properties
const arr = ['UK', 'Region 2', 'Gatwick North'];
if (arr.includes(obj.name)) {
obj.toggled = true;
obj.active = true;
}
}

const recursion = (obj) => {
const o = obj;
checkAndChange(o); // check if name exists in array and change toggle and active properties
if (o.children.length > 0) { // check if has children
o.children.forEach(v => { // if has children do the same recursion for every children
recursion(v);
});
}
return o; // return final new object
}

console.log(recursion(obj));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于Javascript通过数组路径更新嵌套对象中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53497827/

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