【发布时间】:2019-03-23 19:00:16
【问题描述】:
我正在处理从 API 获取的嵌套对象数组:
const myObj = [
{
"$id":"1",
"Description":"WA State",
"Place":"WA",
"Data":[
{
"$id":"2",
"Description":"Years",
"Indicators":[
{
"$id":"3",
"Year":2017,
"Points":22191,
"Goal":"28000",
"Description":"Year 2017"
},
{
"$id":"4",
"Year":2018,
"Points":25994,
"Goal":"28000",
"Description":"Year 2018"
}
]
},
{
"$id":"5",
"Description":"Local Goal",
"Indicators":[
{
"$id":"6",
"Year":2018,
"Points":25994,
"Goal":"28000",
"Description":"Year 2018"
}
]
},
{
"$id":"7",
"Description":"Remote Goal",
"Indicators":[
{
"$id":"8",
"Year":2018,
"Points":55857,
"Goal":"84000",
"Description":"Year 2018"
}
]
}
]
},
{
"$id":"9",
"Description":"NY State",
"Place":"NY",
"Data":[
{
"$id":"10",
"Description":"Years",
"Indicators":[
{
"$id":"11",
"Year":2017,
"Points":23451,
"Goal":"27000",
"Description":"Year 2017"
},
{
"$id":"12",
"Year":2018,
"Points":21953,
"Goal":"26000",
"Description":"Year 2018"
}
]
},
{
"$id":"13",
"Description":"Local Goal",
"Indicators":[
{
"$id":"14",
"Year":2018,
"Points":24195,
"Goal":"25000",
"Description":"Year 2018"
}
]
},
{
"$id":"15",
"Description":"Remote Goal",
"Indicators":[
{
"$id":"16",
"Year":2018,
"Points":80857,
"Goal":"90000",
"Description":"Year 2018"
}
]
}
]
}
];
我需要从对象中删除所有$id 和Description 属性,但不改变对象。我正在尝试使用.reduce():
const props = ['$id', 'Descripcion'];
function removeKeys(obj, prop){
return props.map( (prop, index) => Object.keys(obj).reduce((object, key) => {
if (key !== prop[index]) {
object[key] = obj[key]
}
if(object.hasOwnProperty(key))
removeKeys(obj, prop[index])
return object
}, {})
)
}
console.log( removeKeys(myObj, props) );
// RangeError: Maximum call stack size exceeded
而且不起作用。关于如何使用.reduce()
PD:我的问题不是重复,因为我提到并指定使用reduce 来实现目标。在另一个问题中,答案是关于使用"for...loop" 语法。
【问题讨论】:
-
为什么需要使用
reduce来完成? -
因为我不想改变状态,而且我正在寻找一种优雅的方式来做到这一点。
-
首先,不要担心优雅,而要担心一些有用的东西。听起来你想要一个单独的新数组(对象)?
-
是的,但是...用
reduce来做这件事有点困难? -
有人否决我的答案的原因是什么?我已经用问题作者选择的方法提出了解决方案
标签: javascript arrays object recursion data-manipulation