How to deep filter objects (not object arrays)

2019-09-02 22:32发布

问题:

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'
  }
};

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"?

In this case, it would return ['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. 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.)

回答1:

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'}))