3

I would like to know how to convert enum object to array of objects in javascript

It works, but am getting the output with four object arrays instead of two object arrays

const result = Object.entries(countries).map(([value, key]) =>
   ({ country: value.toLowerCase(), id: key })
);

enum countries {
  SINGAPORE = 123,
  DENMARK = 246
}

Actual Output:

[
  {country: '123', id: 'singapore'}
  {country: '246', id: 'denmark'}
  {country: 'singapore', id: 123}
  {country: 'denmark', id: 246}
]

Expected Output:

[
  {country: "singapore", id: 123},
  {country: "denmark", id: 246}
]
Peter B
  • 22,460
  • 5
  • 32
  • 69
sen
  • 91
  • 7
  • Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Jan 10 '22 at 14:18
  • https://stackoverflow.com/questions/18111657/how-to-get-names-of-enum-entries – epascarello Jan 10 '22 at 14:28

1 Answers1

4

It's important to understand the JavaScript that typescript generates when you use enum - yours will look like this:

{
    "123":"SINGAPORE",
    "246":"DENMARK",
    "SINGAPORE":123,
     "DENMARK":246
}

Which should make it clear why you get 4 items when you enumerate it using Object.entries (or Object.keys etc).

You can filter out the numeric values if you wish

var countries = {
        "123":"SINGAPORE",
        "246":"DENMARK",
        "SINGAPORE":123,
         "DENMARK":246
    }

const result = Object.entries(countries)
                    .filter(([key,_]) => !isNaN(key))
                    .map(([key, value]) => ({ country: value.toLowerCase(), id: key }));
                    
console.log(result);
Jamiec
  • 133,658
  • 13
  • 134
  • 193