1 回答

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個贊
您可以使用_.intersectionWith()從數(shù)組中獲取項(xiàng)目objects,它id等于ids數(shù)組中的項(xiàng)目:
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>
另一種選擇是將數(shù)組轉(zhuǎn)換為using (the )objects的對象,然后使用using 從字典中獲取項(xiàng)目:{ [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>
添加回答
舉報(bào)