我在尝试更改嵌套对象数组中特定 属性的值时遇到问题:
const myObj = [
{
"Description":"WA State",
"Data":[
{
"Description":"Years",
"Indicators":[
{
"Year":2018,
"Points":25994,
"Goal":"28000",
}
]
},
{
"Description":"Local Goal",
"Indicators":[
{
"Year":2018,
"Points":25994,
"Goal":"28000",
}
]
},
{
"Description":"Remote Goal",
"Indicators":[
{
"Year":2018,
"Points":55857,
"Goal":"84000",
}
]
}
]
},
{
"Description":"NY State",
"Data":[
{
"Description":"Years",
"Indicators":[
{
"Year":2018,
"Points":21953,
"Goal":"26000",
}
]
},
{
"Description":"Local Goal",
"Indicators":[
{
"Year":2018,
"Points":24195,
"Goal":"25000",
}
]
},
{
"Description":"Remote Goal",
"Indicators":[
{
"Year":2018,
"Points":80857,
"Goal":"90000",
}
]
}
]
}
]
在这里,我需要将 Year
属性的所有外观更改为 2017
,并将 Goal
属性的所有外观更改为: 50000
.
我正在考虑拥有一个对象数组,我可以在其中声明如下内容:
const newValues = [{property: 'Year', newValue: 2019}, {property: 'Goal', newValue: 50000}]
然后使用它来比较使用 filter
或 reduce
迭代对象的嵌套数组?有什么想法或建议吗?
最佳答案
要以递归方式执行此操作而不依赖于父键,您可以尝试组合使用 map
和 forEach
。
const myObj = [
{
Description: "WA State",
Data: [
{
Description: "Years",
Indicators: [
{
Year: 2018,
Points: 25994,
Goal: "28000"
}
]
},
{
Description: "Local Goal",
Indicators: [
{
Year: 2018,
Points: 25994,
Goal: "28000"
}
]
},
{
Description: "Remote Goal",
Indicators: [
{
Year: 2018,
Points: 55857,
Goal: "84000"
}
]
}
]
},
{
Description: "NY State",
Data: [
{
Description: "Years",
Indicators: [
{
Year: 2018,
Points: 21953,
Goal: "26000"
}
]
},
{
Description: "Local Goal",
Indicators: [
{
Year: 2018,
Points: 24195,
Goal: "25000"
}
]
},
{
Description: "Remote Goal",
Indicators: [
{
Year: 2018,
Points: 80857,
Goal: "90000"
}
]
}
]
}
];
function parse(arr) {
return arr.map(obj => {
Object.keys(obj).forEach(key => {
if (Array.isArray(obj[key])) {
parse(obj[key]);
}
if (key === 'Year') {
obj[key] = 2017;
}
if (key === 'Goal') {
obj[key] = 50000;
}
})
return obj;
})
}
console.log(parse(myObj));
关于javascript - 从嵌套的对象数组递归更改特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52884640/