Lodash, find every object given an array of ids

Viewed 1170

What I have works, but I have a suspicion that there is a lodash method that can do this without the _.map().

const _ = require('lodash')
const ids = [1, 2]
const objects = [
  {
    id: 1,
    foo: 'bar'
  }, {
    id: 2,
    foo: 'baz'
  }, {
    id: 3,
    foo: 'quux'
  }
]

const result = _.map(ids, id => _.find(objects, { id }))
console.log(result)
// => [ { id: 1, foo: 'bar' }, { id: 2, foo: 'baz' } ]

Thanks!

1 Answers

You can use _.intersectionWith() to get items from the objects array, which id is equal to an item in the ids array:

const ids = [1, 2]
const objects = [{ id: 1, foo: 'bar' }, { id: 2, foo: 'baz' }, { id: 3, foo: 'quux' }]

const result = _.intersectionWith(objects, ids, (o, id) => o.id === id)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

Another option is to convert the objects array to a object of { [id]: obj } using _.keyBy() (the id), and then using _.at() to get the items from the dictionary using _.at():

const ids = [1, 2]
const objects = [{ id: 1, foo: 'bar' }, { id: 2, foo: 'baz' }, { id: 3, foo: 'quux' }]

const result = _.at(_.keyBy(objects, 'id'), ids)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

Related