目前,我通过执行以下操作找到嵌套对象
let optionToRemove = newSections.find((section) => section.id == this.state.currentSectionId).questions
.find((question) => question.id == questionId).options
.find((option) => option.id == optionId)
这看起来很乏味,有没有更简单的方法呢?
答案 0 :(得分:0)
有几种方法可以实现这一目标,顺便说一下:
var findNested = function(obj, key, memo) {
var i,
proto = Object.prototype,
ts = proto.toString,
hasOwn = proto.hasOwnProperty.bind(obj);
if ('[object Array]' !== ts.call(memo)) memo = [];
for (i in obj) {
if (hasOwn(i)) {
if (i === key) {
memo.push(obj[i]);
} else if ('[object Array]' === ts.call(obj[i]) || '[object Object]' === ts.call(obj[i])) {
findNested(obj[i], key, memo);
}
}
}
return memo;
}
所以你可以像
一样使用它
var findNested = function(obj, key, memo) {
var i,
proto = Object.prototype,
ts = proto.toString,
hasOwn = proto.hasOwnProperty.bind(obj);
if ('[object Array]' !== ts.call(memo)) memo = [];
for (i in obj) {
if (hasOwn(i)) {
if (i === key) {
memo.push(obj[i]);
} else if ('[object Array]' === ts.call(obj[i]) || '[object Object]' === ts.call(obj[i])) {
findNested(obj[i], key, memo);
}
}
}
return memo;
}
console.log( findNested({ key: 1}, "key") )
console.log( findNested({ key: 1, inner: { key:2}}, "key") )
console.log( findNested({ key: 1, inner: { another_key:2}}, "another_key") )