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?
Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) .
As list. toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.
data convert to array by using useState([]) as initial value and convert to object by using useState({}) .
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:
Array.prototype.map()
Object.keys()
Assuming your object instance is named obj
:
Object.keys(obj).reduce((acc, curr) => {
return [...acc, { id: curr, name: obj[curr] }]
}, [])
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]
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With