Search code examples
javascriptlodash

Filter objects in array by key-value pairs


I have an array of objects like so:

    [
      {
        id: 'a',
        name: 'Alan',
        age: 10
      },
      {
        id: 'ab'
        name: 'alanis',
        age: 15
      },
      {
        id: 'b',
        name: 'Alex',
        age: 13
      }
    ]

I need to pass an object like this { id: 'a', name: 'al' } so that it does a wildcard filter and returns an array with the first two objects.

So, the steps are:

  1. For each object in the array, filter the relevant keys from the given filter object

  2. For each key, check if the value starts with matching filter object key's value

At the moment I'm using lodash's filter function so that it does an exact match, but not a start with/wildcard type of match. This is what I'm doing:

filter(arrayOfObjects, filterObject)


Solution

  • I think you're looking for something like this? Would basically be doing a string.includes match on the value of each key in your filter object--if one of the key values matches then it will be included in the result. If you wanted the entire filter object to match you could do .every instead of .some...

    const data = [
      {
        id: 'a',
        name: 'Alan',
        age: 10
      },
      {
        id: 'ab',
        name: 'alanis',
        age: 15
      },
      {
        id: 'b',
        name: 'Alex',
        age: 13
      }
    ]
    
    const filter = { id: 'a', name: 'al' }
    
    function filterByObject(filterObject, data) {
      const matched = data.filter(object => {
        return Object.entries(filterObject).some(([filterKey, filterValue]) => {
          return object[filterKey].includes(filterValue)
        })
      })
      return matched
    }
    
    console.log(filterByObject(filter, data))