Reputation: 1078
This might looks stupid, but i'm lost. I want to Map through countries and regions array. I have a Countries Array
that also includes Region's Array
. I can access the Countries Array, but when i try to access the Regions Array
i returned from the Countries Array
, it returns undefined. Here is a minimal example.
Full code on CodeSandBox
const Countries = [
{
countryName: "Afghanistan",
countryShortCode: "AF",
regions: [
{
name: "Badakhshan",
shortCode: "BDS",
},
{
name: "Badghis",
shortCode: "BDG",
},
{
name: "Helmand",
shortCode: "HEL",
},
{
name: "Herat",
shortCode: "HER",
},
{
name: "Jowzjan",
shortCode: "JOW",
},
{
name: "Kabul",
shortCode: "KAB",
},
{
name: "Kandahar",
shortCode: "KAN",
}
],
},
{
countryName: "Åland Islands",
countryShortCode: "AX",
regions: [
{
name: "Brändö",
shortCode: "BR",
},
{
name: "Eckerö",
shortCode: "EC",
},
{
name: "Sund",
shortCode: "SD",
},
{
name: "Vårdö",
shortCode: "VR",
},
],
}
]
const mappedCountries = Countries.map(({ regions }) => regions);
const mappedRegion = mappedCountries.map(({ name }) => name);
console.log(mappedCountries);
console.log(mappedRegion);
Upvotes: 1
Views: 44
Reputation: 667
You can change your condition inside second map like this to access region's name -
mappedCountries.map(e => e.map(({name}) => name))
Upvotes: 1
Reputation: 8407
you are returing an array in the map method. so the result is an array of arrays.
you need to flatten
your result. an easy alternative would be using reduce
const mappedCountries = Countries.reduce((memo, { regions }) => [...memo, ...regions], []);
const mappedRegion = mappedCountries.map(({ name }) => name);
Upvotes: 1