我必须“过滤”数组中对象的 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)
添加回答
举报
0/150
提交
取消