'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?
Solution 1:[1]
Assuming your object instance is named obj:
Object.keys(obj).reduce((acc, curr) => {
return [...acc, { id: curr, name: obj[curr] }]
}, [])
Solution 2:[2]
the trivial way
var o = {
"1": "Technology",
"2": "Startup",
"3": "IT",
};
var arr = [];
for(var i in o) {
arr.push({
id: i,
number: o[i]
});
};
Solution 3:[3]
Nowadays you can use Object.entries() to turn an object into an array of key-value pairs (also stored as an array).
This allows us to take advantage of array destructuring so we can make this a nice one-liner:
const obj = {
"1": "Technology",
"2": "Startup",
"3": "IT",
};
const result = Object.entries(obj).map(([id, name]) => ({id: +id, name}));
console.log(result);
Adding in a unary plus (+) to turn the id (which is a string) into a number.
Solution 4:[4]
const words = {
told: 64,
mistake: 11,
thought: 16,
bad: 17
}
const results = []
Object.entries(words).map(val => results.push({
text: val[0],
value: val[1]
}))
console.log(results)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | badboy24 |
| Solution 3 | Ivar |
| Solution 4 | Zsolt Meszaros |
