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

从数组中检索对象的最佳方法

从数组中检索对象的最佳方法

炎炎设计 2023-05-25 15:45:45
我必须“过滤”数组中对象的 ID,我找到了这种方法,但我认为这不是最好的方法:const idToCompare = 456MyArray = [{name: 'One, brand: [{id: 456, name:'Hello'},{id: 857, name:'Hi'},{id: 456, name:'Goodbye'},{id: 123, name:'See you'}]} ]所以现在我这样做:let filtered = myArray.map(a => a.brand.filter(b => b.id === idToCompare))Console.log(filtered ) // [[{id: 456, name:'Hello'},{id: 456, name:'Goodbye'}]]我需要 flat() 它有filtered.flat()Console.log(filtered ) // [{id: 456, name:'Hello'},{id: 456, name:'Goodbye'}]我怎样才能以最好的方式或简单的方式做?
查看完整描述

1 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

你可以Array#flatMap取而代之Array#map


const

    array = [{ name: 'One', brand: [{ id: 456, name: 'Hello' }, { id: 857, name: 'Hi' }, { id: 456, name:'Goodbye'}, { id: 123, name: 'See you' }] }],

    idToCompare = 456,

    filtered = array.flatMap(({ brand }) => brand.filter(({ id }) => id === idToCompare));


console.log(filtered)


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

添加回答

举报

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