1 回答
TA贡献2012条经验 获得超12个赞
您可以使用_.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>
另一种选择是将数组转换为using (the )objects的对象,然后使用using 从字典中获取项目:{ [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>
添加回答
举报