我正在使用如下所示的 JS 数据结构:
table = {
row1: {
col1: 'A',
col2: 'B',
col3: 'C'
},
row2: {
col1: 'D',
col2: 'A',
col3: 'F'
},
row3: {
col1: 'E',
col2: 'G',
col3: 'C'
}
};
你们如何使用 JavaScript 的 native 过滤器/映射/减少函数来过滤此对象,以生成包含属性 col3 = "C"的行对象键数组?
在这种情况下,它将返回['row1', 'row3']
。
这是我最初根据 another answer 提出的解决方案:
Object.keys(Object.keys(table).reduce(function(accumulator, currentValue) {
if (table[currentValue].col3==='C') accumulator[currentValue] = table[currentValue];
return accumulator;
}, {}));
但是,我接受了下面使用 filter()
的解决方案,因为它更有效。接受的答案是 ES6 语法,但 ES5 语法是由 @Paulpro 提供的:
Object.keys(table).filter(function(row) {
return table[row].col3==='C';
});
(请注意,有 similar solutions ,但它们使用自定义函数,并且不如下面提供的接受的答案那么简洁。)
最佳答案
您可以使用Object.keys
,然后使用原始对象进行过滤:
table = {
row1: {
col1: 'A',
col2: 'B',
col3: 'C'
},
row2: {
col1: 'D',
col2: 'A',
col3: 'F'
},
row3: {
col1: 'E',
col2: 'G',
col3: 'C'
}
};
console.log(Object.keys(table).filter(function(t) { return table[t].col3 === 'C'}))
关于javascript - 如何深度过滤对象(不是对象数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50012040/