-1

How to convert object to array object?

input:

{
  AF: 'Afghanistan',
  AX: 'Åland Islands',
  AL: 'Albania',
  DZ: 'Algeria'
}

output:

[
    {value: 'AF', label: 'Afghanistan'},
    {value: 'AX', label: 'Åland Islands'},
    {value: 'AL', label: 'Albania'},
    {value: 'DZ', label: 'Algeria'}
]
angie
  • 59
  • 5

1 Answers1

2

Use Object.keys() to get the keys of the object. This method returns an array with the keys of the object as string entries. Then map that array, and return the desired object in the mapping function, the result will be the desired array.

let countries = {
  AF: 'Afghanistan',
  AX: 'Åland Islands',
  AL: 'Albania',
  DZ: 'Algeria'
}

let arr = Object.keys(countries).map(key => {
   return {key: key, value: countries[key]}
});
console.log(arr);
Tschallacka
  • 27,901
  • 14
  • 88
  • 133