I have a nested JSON object that getting from a mongoDB query that i would like to convert into flat JSON array .I am using nested mondo documents, but i would like to show the data in a more readble way. My JSON has the following structure:
JavaScript
x
26
26
1
{
2
"country": "Country A",
3
"_id": "1"
4
"regions": [{
5
"region": "region A1",
6
"cities": [{
7
"city": "city A11"
8
},
9
{
10
"city": "city A12"
11
}
12
]
13
},
14
{
15
"region": "region A2",
16
"cities": [{
17
"city": "city A21"
18
},
19
{
20
"city": "city A22"
21
}
22
]
23
}
24
]
25
}
26
I want to show only the important information and not the structure of the nested array. How i can modify my data in Javascript on order to achieve the following result.
JavaScript
1
19
19
1
[{
2
"country": "Country A",
3
"region":"Region A1",
4
"city": "City A11"
5
},
6
{
7
"country": "Country A",
8
"region":"Region A1",
9
"city": "City A12"
10
},
11
12
-------------
13
14
{
15
"country": "Country A",
16
"region":"Region A2",
17
"city": "City A22"
18
}]
19
I have tried to do in this way but it´s not working.
JavaScript
1
18
18
1
exports.get_places = (req, res, next) => {
2
Place.findOne({_id:req.params.id})
3
.then(data => {
4
let flat = arr.reduce((arr, {country, regions}) => {
5
regions.forEach(({region, cities}) => {
6
cities.forEach(({city}) => {
7
arr.push({country, region, city})
8
})
9
})
10
return arr
11
}, [])
12
console.log(flat)
13
})
14
.catch(error => {
15
return next(error);
16
});
17
}
18
Advertisement
Answer
I believe this will perform the transformation you seek:
JavaScript
1
34
34
1
const country = {
2
"country": "Country A",
3
"_id": "1",
4
"regions": [
5
{
6
"region": "region A1",
7
"cities": [
8
{
9
"city": "city A11"
10
},
11
{
12
"city": "city A12"
13
}
14
]
15
},
16
{
17
"region": "region A2",
18
"cities": [
19
{
20
"city": "city A21"
21
},
22
{
23
"city": "city A22"
24
}
25
]
26
}
27
]
28
};
29
30
const flat = country.regions.flatMap(({region, cities}) =>
31
cities.map(({city}) => ({country: country.country, region, city})
32
));
33
34
console.log(flat);