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,

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 0country_code using the value in 1cities 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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With