Skip to content
Advertisement

How to extract all arrays in json object

I have a json object which has a collection of countries. Each country can have multiple regions which are represented in an array. I want to get the regions only and put all regions into one list.However when I map the data it doesn’t put all the regions in a list. What am I missing here?

Here is the call to get the json – i am trying to just get the regions:

this.service.getData().subscribe((data: any) => {
      this.list = data.map((c:any) => c.Regions);
    });

the json object:

{

    "Country": "Antarctica",
    "Regions": [
        "Adélie Land",
        "Argentine Antarctica",
        "Australian Antarctic Territory",
        "British Antarctic Territory",
        "Chilean Antarctic Territory",
        "Peter I Island",
        "Queen Maud Land",
        "Ross Dependency"
    ]
},
{
    "Country": "Antigua And Barbuda",
    "Regions": []
},
{
    "Country": "Argentina",
    "Regions": [
        "Buenos Aires",
        "Cordoba",
        "Buenos Aires City",
        "Catamarca",
        "Chaco",
        "Chubut",
        "San Luis",
        "Santa Cruz",
        "Santa Fe",
        "Santiago del Estero",
        "Tierra del Fuego",
        "Tucuman",
        "Mendoza",
        "Misiones",
        "Neuquen",
        "Rio Negro",
        "Salta",
        "San Juan",
        "Corrientes",
        "Entre Rios",
        "Formosa",
        "Jujuy",
        "La Pampa",
        "La Rioja"
    ]
},

Advertisement

Answer

you can use flatMap for that

like this

const extract = data => data.flatMap(d => d.Regions)

const data = [{

    "Country": "Antarctica",
    "Regions": [
        "Adélie Land",
        "Argentine Antarctica",
        "Australian Antarctic Territory",
        "British Antarctic Territory",
        "Chilean Antarctic Territory",
        "Peter I Island",
        "Queen Maud Land",
        "Ross Dependency"
    ]
},
{
    "Country": "Antigua And Barbuda",
    "Regions": []
},
{
    "Country": "Argentina",
    "Regions": [
        "Buenos Aires",
        "Cordoba",
        "Buenos Aires City",
        "Catamarca",
        "Chaco",
        "Chubut",
        "San Luis",
        "Santa Cruz",
        "Santa Fe",
        "Santiago del Estero",
        "Tierra del Fuego",
        "Tucuman",
        "Mendoza",
        "Misiones",
        "Neuquen",
        "Rio Negro",
        "Salta",
        "San Juan",
        "Corrientes",
        "Entre Rios",
        "Formosa",
        "Jujuy",
        "La Pampa",
        "La Rioja"
    ]
}]

console.log(extract(data))
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement