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

我必须“过滤”数组中对象的 ID,我找到了这种方法,但我认为这不是最好的方法:


const idToCompare = 456


MyArray = [{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'}]

我怎样才能以最好的方式或简单的方式做?


炎炎设计
浏览 93回答 1
1回答

aluckdog

你可以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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript