alex
alex

Reputation: 7601

How to find many results from an array with Lodash?

The following code loops thorugh an Object array, uses _.find to find the object of a certain category and push it into the panoramaCats array:

this.panoramas.forEach(panorama => {
  const panoramaCat = _.find(this.panoramas, { category: panorama.category })
  const panoramaCats = []
  panoramaCats.push(panoramaCat)
  payload[panorama.category] = panoramaCats
})

I thought _.find would find ALL the objects with that category, but it only finds the first one.

How to change the code so _.find finds ALL the object with that category?

Upvotes: 0

Views: 264

Answers (3)

Frances McMullin
Frances McMullin

Reputation: 5696

Have you considered using _.groupBy? I think it's simpler than manually looping through your collection.

payload = _.groupBy(this.panoramas, 'category')

If you need to preserve other pre-existing properties in your payload object you could use _.merge:

payload = _.merge(payload, _.groupBy(this.panoramas, 'category'))

Upvotes: 0

stasovlas
stasovlas

Reputation: 7416

this.panoramas.forEach(panorama => {
    payload[panorama.category] = _.find(this.panoramas, {category: panorama.category})
})

Upvotes: 0

Wojciech Zylinski
Wojciech Zylinski

Reputation: 2035

Use ._matches to find objects matching your criteria.

this.panoramas.forEach(panorama => {
  const panoramaCats = _.find(this.panoramas, _.matches({ category: panorama.category }))
  payload[panorama.category] = panoramaCats
})

Upvotes: 1

Related Questions