简体   繁体   中英

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?

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
})
this.panoramas.forEach(panorama => {
    payload[panorama.category] = _.find(this.panoramas, {category: panorama.category})
})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM