Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Javascript array of countries into new array

Alright, so I have a package react-country-region-selector that provides me with an array CountryRegionData, when I console log it, it's an array of 248 countries,

enter image description here

As you can see in the image for Italy for example, 0 is country name, 1 is country code, 2 is an string of cities seperated by an | and their codes seperated by an ~.

what I would like to do is map this array into a new one, where for each entry it's reformatted to have 3 properties,

  • country_name using the value in 0
  • country_code using the value in 1
  • cities containing an array which has a sub-array for each city that has city_name using the value before the ~ and city_code containing the value after the ~.

I understand this is a bit overwhelming but I'm hoping it would be possible to do using a map function.

Thank you.

like image 710
Omar Hussein Avatar asked Jun 17 '26 04:06

Omar Hussein


2 Answers

You can get the desired structure by mapping over the array itself and mapping over cities of every country inside the arary:

const CountryRegionData = [['Andorra', 'AD', 'Andorra la Vella~07|Canillo~02'], ['Angola', 'AO', 'Bengo~BGO|Benguela~BGU']];
const result = CountryRegionData.map(([country_name, country_code, cities]) => ({
    country_name,
    country_code,
    cities: cities
      .split('|')
      .map(cityData => cityData.split('~'))
      .map(([city_name, city_code]) => ({ city_name, city_code }))
}));

console.log(result)
like image 168
antonku Avatar answered Jun 18 '26 18:06

antonku


Here is a destructing version that creates an object array as I assume you meant

let res = [
  ["Italy", "IT", "Abruzzo~65|Basilicata~77|Calabria~89"],
  ["Italy2", "IT2", "Abruzzo~65|Basilicata~77|Calabria~89"],
  ["Italy3", "IT3", "Abruzzo~65|Basilicata~77|Calabria~89"],
  ["Italy4", "IT4", "Abruzzo~65|Basilicata~77|Calabria~89"],
].map(item => {
  const [country_code, country_name, ...rest] = item;
  return {country_code, country_name, cities : 
    rest.map(item => {
        return item.split("|").map(city => { 
          const [city_name, city_code] = city.split("~")
          return {city_name, city_code}
        })
    }).flat()
  }  
});
console.log(res)
like image 35
mplungjan Avatar answered Jun 18 '26 17:06

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!