如何深层过滤对象(不是对象数组) [英] How to deep filter objects (not object arrays)
问题描述
我正在使用看起来像这样的JS数据结构:
I'm working with a JS data structure that looks something like this:
table = {
row1: {
col1: 'A',
col2: 'B',
col3: 'C'
},
row2: {
col1: 'D',
col2: 'A',
col3: 'F'
},
row3: {
col1: 'E',
col2: 'G',
col3: 'C'
}
};
你们将如何使用JavaScript的本机filter/map/reduce函数过滤该对象,以生成包含属性col3 ="C"的行对象键的数组?
How would you guys filter this object using JavaScript's native filter/map/reduce functions to produce an array of row object keys that contain the property col3 = "C"?
在这种情况下,它将返回['row1', 'row3']
.
In this case, it would return ['row1', 'row3']
.
这是我最初基于另一个答案:
Object.keys(Object.keys(table).reduce(function(accumulator, currentValue) {
if (table[currentValue].col3==='C') accumulator[currentValue] = table[currentValue];
return accumulator;
}, {}));
但是,我已经接受了使用filter()
的以下解决方案,因为它效率更高.可接受的答案使用ES6语法,但是ES5语法由@Paulpro提供:
However, I have accepted the solution below using filter()
because it's more efficient. The accepted answer is in ES6 syntax, but ES5 syntax was provided by @Paulpro:
Object.keys(table).filter(function(row) {
return table[row].col3==='C';
});
(请注意,这里有类似的解决方案,但它们使用自定义功能,并且不如所提供的可接受的答案那么简洁下方.)
(Note that there are similar solutions out there, but they use custom functions and are not as concise as the accepted answer provided below.)
推荐答案
您可以使用Object.keys
,然后使用原始对象进行过滤:
You could use Object.keys
and then filter using the original object:
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'}))
这篇关于如何深层过滤对象(不是对象数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!