Search code examples
javascriptecmascript-6lodash

JavaScript or Lodash find objects by key


In an array of objects with diff keys, how do I find objects by key using ES6 or Lodash?

const arr = [{a:2}, {b:3}, {fred:10}]

I want the result to be:

=> [{a:2}, {fred:10}]

I don't want to use an omit style approach.


Solution

  • Basically you want all the objects from the array who have the fields a or fred. You can use the hasOwnProperty() on the objects while filtering.

    _.filter(array, elem => elem.hasOwnProperty('a') || elem.hasOwnProperty('fred'));