3

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 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

1 Comment

I'm looking for the same, but in plain JS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.