I have this array of object, within it I have another array of object, how to get:
[
{ id: "5a60626f1d41c80c8d3f8a85" },
{ id: "5a6062661d41c80c8b2f0413" },
{ id: "5a60626f1d41c80c8d3f8a83" },
{ id: "5a60626f1d41c80c8d3f8a84" }
];
From:
[
{
id: 1,
country: [
{
id: "5a60626f1d41c80c8d3f8a85"
},
{
id: "5a6062661d41c80c8b2f0413"
}
]
},
{
id: 2,
country: [
{
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.
This, works, just concat the nested arrays returned by your solution
Ayush Gupta's solution will work for this case. But I would like to provide other solution.
For JSON string data, it can be done during parsing too :
No need for any ES6 magic, you can just reduce the array by concatenating inner
country
arrays.If you want an ES6 feature (other than an arrow function), use array spread instead of the concat method:
Note: These suggestions would create a new array on each iteration.
For efficiency, you have to sacrifice some elegance: