Search code examples
javascriptarraysobjectfilterjavascript-objects

filter array of objects based on separate object keys, values


I have the array of people below:

  const FIRST_ARRAY = [
    {
      name: 'Simon',
      age: 32,
      occupation: 'Student'
    },
    {
      name: 'Vera',
      age: 22,
      occupation: 'Developer'
    }
  ];

I would like to filter the array to produce a separate array based on a 'filters' object.

For example if my filters are:

  const FILTERS = {
    age: 32,
    name: 'John',
    occupation: ''
  };

The new array should be empty as no people in the array have the combination of 32 and John. However if my filters are:

 const FILTERS = {
    age: 32,
    name: 'Simon',
    occupation: ''
  }

The new array of people returned will be:

 const NEW_ARRAY = [
    {
      name: 'Simon',
      age: 32,
      occupation: 'Student'
    }
  ];

How can I filter the array of people by iterating over the 'filters' object values? Bare in mind the filters keys and values will dynamically changing all the time.


Solution

  • You could filter as follows:

    const FIRST_ARRAY = [
      {
        name: 'Simon',
        age: 32,
        occupation: 'Student'
      },
      {
        name: 'Vera',
        age: 22,
        occupation: 'Developer'
      }
    ];
    
    const FILTERS = {
      name: 'Simon',
      age: 32,
      occupation: ''
    };
    
    const filtered = FIRST_ARRAY.filter(person => Object.entries(FILTERS)
      .every(([key, val]) => val !== '' ? person[key] === val : true));
      
    console.log(filtered);