0

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?

1
  • So you want to get all productOrders from each object in this.orders in a single flat array? Commented Jun 10, 2020 at 2:09

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

3 Comments

thank you. That's exactly what I was looking for. But at first I couldn't use the flat() function. I had to add esnext in the lib section of tsconfig.json file to make it work. Now my concern is does it cause browser compatibility or Typescript transpiles to ES2015 as mentioned in the target of the file.
If you're targeting ES2015 then TS will transpile your code so it's compatible with that. Why not try adding this code in the TypeScript Playground with the target set so you can see exactly what your code will get transpiled to? 🙂

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.