I have this array of objects, within it I have another array of objects:
[ { id: 1, country: [ { id: "5a60626f1d41c80c8d3f8a85" }, { id: "5a6062661d41c80c8b2f0413" } ] }, { id: 2, country: [ { id: "5a60626f1d41c80c8d3f8a83" }, { id: "5a60626f1d41c80c8d3f8a84" } ] } ];
How to get flat array of country
like this:
[ { id: "5a60626f1d41c80c8d3f8a85" }, { id: "5a6062661d41c80c8b2f0413" }, { id: "5a60626f1d41c80c8d3f8a83" }, { id: "5a60626f1d41c80c8d3f8a84" } ];
without using a forEach
and a temp variable?
When I did:
(data || []).map(o=>{ return o.country.map(o2=>({id: o2.id})) })
I got the same structure back.
Advertisement
Answer
Latest edit
All modern JS environments now support Array.prototype.flat
and Array.prototype.flatMap
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}]; console.log( data.flatMap( (elem) => elem.country ) )
Old answer
No need for any ES6 magic, you can just reduce the array by concatenating inner country
arrays.
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}]; console.log( data.reduce( (arr, elem) => arr.concat(elem.country), [] ) )
If you want an ES6 feature (other than an arrow function), use array spread instead of the concat method:
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}]; console.log( data.reduce( (arr, elem) => [...arr, ...elem.country], [] ) )
Note: These suggestions would create a new array on each iteration.
For efficiency, you have to sacrifice some elegance:
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}]; console.log( data.reduce( (arr, elem) => { for (const c of elem.country) { arr.push(c); } return arr; }, [] ) )