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