Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Turn nested for into a one-liner in javascript

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);
  }
 }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading