Skip to content
Advertisement

Convert JSOn object into a flat JSON Array

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);
    });
}

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement