Reputation: 803
I have two objects Order and ProductOrder.
Order Object:
{
id:number;
productOrders: ProductOrder[];
}
ProductOrder object:
{
id: number;
productName: string;
}
now i have an array of Order object stored in orders variable:
const orders: Order[];
Now I want to loop through each order and and further loop through each ProductOrder and return an array of all the ProductOrders.
Using forEach loop we can do this in the following way:
const productOrders: ProductOrder[] = [];
this.orders.forEach(o => {
o.productOrders.forEach(po => {
productOrders.push(po);
});
});
Now I want to know instead of using two forEach loop and then adding each productOrder in a pre declared array, is there a simpler way to achieve this using map function or something else?
Upvotes: 0
Views: 1339
Reputation: 9248
I'm not 100% clear on what you're looking for but if I understand you correctly then this will do what you need:
const productOrders = orders.map(order => order.productOrders).flat();
// const productOrders: ProductOrder[]
It's worth reading into the MDN docs for Array#map()
and Array#flat()
to see what they do as they can be very useful!
Upvotes: 3