简体   繁体   English

如何深层过滤对象(不是对象数组)

[英]How to deep filter objects (not object arrays)

I'm working with a JS data structure that looks something like this: 我正在使用看起来像这样的JS数据结构:

table = {
  row1: {
    col1: 'A',
    col2: 'B',
    col3: 'C'
  },
  row2: {
    col1: 'D',
    col2: 'A',
    col3: 'F'
  },
  row3: {
    col1: 'E',
    col2: 'G',
    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"? 你们将如何使用JavaScript的本机filter / map / reduce函数过滤该对象,以生成包含属性col3 =“ C”的行对象键数组?

In this case, it would return ['row1', 'row3'] . 在这种情况下,它将返回['row1', 'row3']

This is a solution that I originally came up with based on another answer : 这是我最初根据另一个答案提出的解决方案:

Object.keys(Object.keys(table).reduce(function(accumulator, currentValue) {
  if (table[currentValue].col3==='C') accumulator[currentValue] = table[currentValue];
  return accumulator;
}, {}));

However, I have accepted the solution below using filter() because it's more efficient. 但是,我接受了使用filter()以下解决方案,因为它效率更高。 The accepted answer is in ES6 syntax, but ES5 syntax was provided by @Paulpro: 可接受的答案是ES6语法,但是ES5语法由@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.) (请注意,那里有类似的解决方案 ,但是它们使用自定义功能,并且不如下面提供的接受的答案那么简洁。)

You could use Object.keys and then filter using the original object: 您可以使用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'})) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM