I have an object that looks like this:
JavaScript
x
6
1
{
2
"1": "Technology",
3
"2": "Startup",
4
"3": "IT",
5
}
6
and I need to convert it to an array of objects that would look like this:
JavaScript
1
6
1
[
2
{id: 1, name: "Technology"},
3
{id: 2, name: "Startup"},
4
{id: 3, name: "IT"}
5
]
6
What would be the cleanest & efficient way to do this?
Advertisement
Answer
You can use .map()
with Object.keys()
:
JavaScript
1
10
10
1
let data = {
2
"1": "Technology",
3
"2": "Startup",
4
"3": "IT",
5
};
6
7
let result = Object.keys(data)
8
.map(key => ({id: Number(key), name: data[key]}));
9
10
console.log(result);
Useful Resources: