Search code examples
javascripttypescriptinternationalization

Typescript JSON to Array


I'm trying to create an Array with a Key and a Value from a JSON. I'm working with i18n-iso-countries lib. I have got in a variable all countries from the countries lib in this JSON format:

{
  AD: "Andorra",
  AE: "United Arab Emirates",
  AF: "Afghanistan",
  AG: "Antigua and Barbuda",
  etc...
}

But in JSON format.

I know I can transform the JSON into an object with Object.values(countries), but doing it like this, the Key is lost and I get this format:

{
  0: "Afghanistan"
  1: "Albania"
  2: "Algeria"
  3: "American Samoa"
}

All I want is a new Array like this:

[
  {
    id: 'AD'
    country: 'Andorra'
  },
  {
    id: 'AE'
    country: 'United Arab Emirates'
  }
]

etc...

I suppose it is something to do with forEach my countries and add id as Key and country as Value, but I can't resolve it.

Thanks!


Solution

  • You can use Object.entries() to get an array of key-value pairs from an object:

    const countries = {
      AD: "Andorra",
      AE: "United Arab Emirates",
      AF: "Afghanistan",
      AG: "Antigua and Barbuda"
    }
    
    const countriesArray = Object.entries(countries).map(([id, country]) => ({ id, country }))
    
    console.log(countriesArray)