为了账号安全,请及时绑定邮箱和手机立即绑定

Lodash,找到给定 ids 数组的每个对象

Lodash,找到给定 ids 数组的每个对象

潇潇雨雨 2023-06-29 22:30:04
我所拥有的有效,但我怀疑有一个 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' } ]谢谢!
查看完整描述

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>


查看完整回答
反对 回复 2023-06-29
  • 1 回答
  • 0 关注
  • 178 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信