Map Javascript array of countries into new array - Stack Overflow

Alright, so I have a package react-country-region-selector that provides me with an array CountryRegion

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 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.

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 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.

Share Improve this question edited Nov 14, 2019 at 13:47 Omar Hussein asked Nov 14, 2019 at 13:24 Omar HusseinOmar Hussein 1,1472 gold badges15 silver badges33 bronze badges 5
  • 3 Please, post the code you are using to try to solve your problem and then we can debug and help with a good solution – Calvin Nunes Commented Nov 14, 2019 at 13:27
  • Agree with @CalvinNunes. What have you tried up to now? Are we sure that 3rd item is an array? Could it be a string? – devserkan Commented Nov 14, 2019 at 13:29
  • 1 It is definitely possible to do using a map function... It involves mapping over the main array and returning objects (and possibly having to split a string inside and map on that too to get your sub array). Give it a shot and post your code here as suggested by @CalvinNunes if you face any more problems :) – Chirag Ravindra Commented Nov 14, 2019 at 13:29
  • Please visit help center, take tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output. – mplungjan Commented Nov 14, 2019 at 13:37
  • 1 FYI: those are not cities. At least for Italy those are regions. – Federico klez Culloca Commented Nov 14, 2019 at 13:52
Add a ment  | 

9 Answers 9

Reset to default 2

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)

The quick and dirty version...

const rawCountries = [['Italy', 'IT', 'Abruzzo~65|Basilicata~77']];

const countries = rawCountries.map(rawCountry => ({
    country_name: rawCountry[0],
    country_code: rawCountry[1],
    cities: rawCountry[2].split('|').map(rawCity => {
      const cityTuple = rawCity.split('~');
      return { city_name: cityTuple[0], city_code: cityTuple[1] };
    })
}));

console.log(countries);

Should be more maintainable over time...

const rawCountries = [['Italy', 'IT', 'Abruzzo~65|Basilicata~77']];


const parseCountries = (() => {
  return (rawCountries) => rawCountries.map(parseCountry);
  
  function parseCountry(rawCountry) {
    return {
      country_name: rawCountry[0],
      country_code: rawCountry[1],
      cities: parseCities(rawCountry[2])
    };
  }
  
  function parseCities(rawCities) { 
    return rawCities.split('|').map(parseCity);
  }
  
  function parseCity(rawCity) {
    const countryCodeTuple = rawCity.split('~');
    return { 
      city_name: countryCodeTuple[0], 
      city_code: countryCodeTuple[1] 
    };
  }
})();

console.log(parseCountries(rawCountries));

Here is a clean and simple solution to this:-

function formatCountries(countryArray) {
    var result = [];

    countryArray.forEach(country => {
        result.push({ country_name: country[0], country_code: country[1], cities: getCities(country[2]) });
    });

    return result;
}

function getCities(cityStr) {
    const cityAndCodeArr = cityStr.split('|');
    const result = [];

    cityAndCodeArr.forEach(item => {
        const tempArr = item.split('~');
        result.push({ city_name: tempArr[0], city_code:  tempArr[1]});
    });

    return result;
}

// call the formatCountries function like following
formatCountries(data);

You can use a bination of array reduce and array map to create a new country array

let originalArray = <Your array>
let newCountryArray = originalArray.reduce((newArray, currentElement) => {

    let newObj = {};
    newObj.country_name = currentElement[0];
    newObj.country_code = currentElement[1];

    let cities = currentElement[2];
    cities = cities.split('|');
    cities = cities.map(city => {
        city = city.split('~');
        return {
            city_name: city[0],
            city_code: city[1]
        };
    });

    newObj.cities = cities;
    newArray.push(newObj);

    return newArray;
}, []);

I have made a working snippet for you. You can customize the variables acording to your needs.

let ar = [
  ["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"],
]

let newAr = ar.map((x) => {
  let cities = x[2].split("|");
  let citiesAr = cities.map((y) => {
    city = y.split("~");
    return {
        city_name: city[0],
        city_code: city[1]
    };
  })
  return {country_name: x[0], country_code: x[1],  cities: citiesAr}
})

console.log(newAr)

let ar =  [
  ["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"],
]


    let newCountryList = [];
ar.reduce((arr, curr) => {
  // debugger;

  let newContList = {
    country_name: curr[0],
    country_code: curr[1],
    cities: []
  }

  let newCities = [];
  curr[2].split('|').reduce((ar1, ele) => {
    let city = ele.split('~');
    newCities.push({ city_name: city[0], city_code: city[1] })
  }, [])

  newContList.cities = newCities;
  newCountryList.push(newContList);

}, [])

console.log(newCountryList)

hope this helps...

Yep, the map function.

const CountryRegionData = [
      ["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"],
    ];

    const mappedCountries = CountryRegionData.map(data => {
      const cityArray = data[2]
                          .split('|')
                          .map(item => {
                             const cities = item.split('~');
                             return {
                                city_name: cities[0],
                                city_code: cities[1]
                             }
                          });
      return {
         country_name: data[0],
         country_code: data[1],
         cities: cityArray
      };
    });
    
    console.log(mappedCountries);

You can do this way using the map function of the array :

// Data set
const data = [
  ["Italy", "IT", "Abruzzo~65|AnotherCity~70"],
  ["Spain", "SP", "City~12|AnotherCity~3"],
]

// Declare the variable that will contain the formatted data
const formattedData = data.map((e) => {
  // Split the cities string in order to get an array ["Abruzzo~65", 
  // "AnotherCity~70]"]
  let citiesArray = e[2].split('|')
  // Map other this array and split around the "~" to get city name 
  // and city code in an array ["Abruzzo", "65"]
  const cities = citiesArray.map((e) => {
    return {
      city_name: e.split('~')[0],
      city_code: e.split('~')[1]
    }
  })
  return {
    country_name: e[0],
    country_code: e[1],
    cities: cities
  }
})

console.log(formattedData)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745349528a4623745.html

相关推荐

  • Map Javascript array of countries into new array - Stack Overflow

    Alright, so I have a package react-country-region-selector that provides me with an array CountryRegion

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信