Skip to content
Advertisement

How to flatten nested array of object using es6

I have this array of objects, within it I have another array of objects:

JavaScript

How to get flat array of country like this:

JavaScript

without using a forEach and a temp variable?

When I did:

JavaScript

I got the same structure back.

Advertisement

Answer

Latest edit

All modern JS environments now support Array.prototype.flat and Array.prototype.flatMap

JavaScript

Old answer

No need for any ES6 magic, you can just reduce the array by concatenating inner country arrays.

JavaScript

If you want an ES6 feature (other than an arrow function), use array spread instead of the concat method:

JavaScript

Note: These suggestions would create a new array on each iteration.

For efficiency, you have to sacrifice some elegance:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement