[英]Lodash, find every object given an array of ids
What I have works, but I have a suspicion that there is a lodash method that can do this without the _.map().我有什么工作,但我怀疑有一种 lodash 方法可以在没有 _.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!谢谢!
You can use _.intersectionWith()
to get items from the objects
array, which id
is equal to an item in the ids
array:您可以使用_.intersectionWith()
从objects
数组中获取项目,其中id
等于ids
数组中的一个项目:
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()
:另一种选择是转换的objects
阵列的对象{ [id]: obj }
使用_.keyBy()
的id
),并且然后使用_.at()
以获得利用来自字典的项目_.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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.