You could use flatMap as suggested by @adiga:
// >=ES2019
const status = this.selectedProjects.flatMap(pr => pr.status)
.find(stat => stat.id === statusId);
Alternatively, if your version supports iterators, you could make a reusable generic function like this:
function* selectMany<TIn, TOut>(
source: Iterable<TIn>,
selector: (item: TIn) => Iterable<TOut>)
: Iterable<TOut> {
for (const item of source) {
const subItems = selector(item);
for (const subItem of subItems) {
yield subItem;
}
}
}
// and while we are at it. Let's make a FirstOrDefault equivalent.
function firstOrNull<T>(source: Iterable<T>, predicate: (item: T) => boolean): T | null {
for (const item of source) {
if (predicate(item)) {
return item;
}
}
return null;
}
Example usage:
interface Item {
elements: Array<number>;
}
const items: Item[] = [
{
elements: [1, 2, 3]
},
{
elements: [4, 5, 6]
}
]
const elements = selectMany(items, itm => itm.elements);
for (const el of elements) {
console.log(el);
}
output:
1
2
3
4
5
6
firstOrNull(elements, itm => itm === 6); // 6
firstOrNull(elements, itm => itm === 7); // null
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…