skip to Main Content

I have this nested for-loop that I am having difficulty turning into a one liner. What is the best way to eliminate the nested for? Thanks.

 for (const house of this.houses){
   for (const room of house.rooms){
   this.plans.push(room.layout.id);
  }
 }

2

Answers


  1. You can try this:

    this.houses.forEach(house => house.forEach(room => this.plans.push(room.layout.id)))
    

    forEach calls a function for each item in an array.

    Login or Signup to reply.
  2. You could map the nested id.

    this.plans = this.houses.flatMap(({ rooms }) => rooms.map(({ layout: { id } }) => id));
    

    For better readability:

    this.plans = this.houses.flatMap(({ rooms }) => rooms
        .map(({ layout: { id } }) => id)
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search