Skip to content
Advertisement

Convert object to an array of objects?

I have an object that looks like this:

{
  "1": "Technology",
  "2": "Startup",
  "3": "IT",
}

and I need to convert it to an array of objects that would look like this:

[
  {id: 1, name: "Technology"},
  {id: 2, name: "Startup"},
  {id: 3, name: "IT"}
]

What would be the cleanest & efficient way to do this?

Advertisement

Answer

You can use .map() with Object.keys():

let data = {
    "1": "Technology",
    "2": "Startup",
    "3": "IT",
};

let result = Object.keys(data)
                   .map(key => ({id: Number(key), name: data[key]}));

console.log(result);

Useful Resources:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement