简体   繁体   English

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

[英]A best way to retrieve object from array

I have to 'filter' the ids of objects who's in array, I find this method but I think is not the best :我必须“过滤”数组中对象的 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'}]} ]

so now I do:所以现在我这样做:

let filtered = myArray.map(a => a.brand.filter(b => b.id === idToCompare))

Console.log(filtered ) // [[{id: 456, name:'Hello'},{id: 456, name:'Goodbye'}]]

I need to flat() it to have我需要 flat() 它有

filtered.flat()
Console.log(filtered ) // [{id: 456, name:'Hello'},{id: 456, name:'Goodbye'}]

How can I do in best way or a simple way ?我怎样才能以最好的方式或简单的方式做?

You could take Array#flatMap instad of Array#map .您可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM