Reputation: 129
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:
{
"country": "Country A",
"_id": "1"
"regions": [{
"region": "region A1",
"cities": [{
"city": "city A11"
},
{
"city": "city A12"
}
]
},
{
"region": "region A2",
"cities": [{
"city": "city A21"
},
{
"city": "city A22"
}
]
}
]
}
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.
[{
"country": "Country A",
"region":"Region A1",
"city": "City A11"
},
{
"country": "Country A",
"region":"Region A1",
"city": "City A12"
},
-------------
{
"country": "Country A",
"region":"Region A2",
"city": "City A22"
}]
I have tried to do in this way but it´s not working.
exports.get_places = (req, res, next) => {
Place.findOne({_id:req.params.id})
.then(data => {
let flat = arr.reduce((arr, {country, regions}) => {
regions.forEach(({region, cities}) => {
cities.forEach(({city}) => {
arr.push({country, region, city})
})
})
return arr
}, [])
console.log(flat)
})
.catch(error => {
return next(error);
});
}
Upvotes: 0
Views: 2738
Reputation: 898
As is the typical case for Node... there's a package for that! A popular one is called flat
(zero deps!!).
https://www.npmjs.com/package/flat
From their README:
var flatten = require('flat')
flatten({
key1: {
keyA: 'valueI'
},
key2: {
keyB: 'valueII'
},
key3: { a: { b: { c: 2 } } }
})
// {
// 'key1.keyA': 'valueI',
// 'key2.keyB': 'valueII',
// 'key3.a.b.c': 2
// }
You can also implement your own! :)
If you need some hints, I've implemented one in a recent project of mine except it returns an array.
Check it out: https://github.com/mster/fireferret/blob/e99b6e8f23d4a0783c8a0706cd163093936d6c69/lib/utils/flatmapper.js#L6-L50
Upvotes: 0
Reputation: 14927
I believe this will perform the transformation you seek:
const country = {
"country": "Country A",
"_id": "1",
"regions": [
{
"region": "region A1",
"cities": [
{
"city": "city A11"
},
{
"city": "city A12"
}
]
},
{
"region": "region A2",
"cities": [
{
"city": "city A21"
},
{
"city": "city A22"
}
]
}
]
};
const flat = country.regions.flatMap(({region, cities}) =>
cities.map(({city}) => ({country: country.country, region, city})
));
console.log(flat);
Upvotes: 1
Reputation: 338
I think you need use map function, and transfomr every object in nested arrays as the object you want to obtain. If I undesrstand you good you will need somthing like this:
let desiredArray = country.region.map(x => {
country:x.country,
region:x.region,
cities:x.city
})
its little confuse to undestand what you really want but I think you can start to work with that
Upvotes: 0