Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 367
Sandra Willford Avatar asked Mar 18 '18 07:03

Sandra Willford


People also ask

How do you convert an object to an array of objects?

Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) .

Can we convert object to array in Java?

As list. toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.

How do you change an object to an array in react?

data convert to array by using useState([]) as initial value and convert to object by using useState({}) .


3 Answers

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()
like image 171
Mohammad Usman Avatar answered Oct 04 '22 21:10

Mohammad Usman


Assuming your object instance is named obj:

Object.keys(obj).reduce((acc, curr) => {
    return [...acc, { id: curr, name: obj[curr] }]
}, [])
like image 36
SALEH Avatar answered Oct 04 '22 21:10

SALEH


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]
    });
};
like image 41
badboy24 Avatar answered Oct 04 '22 21:10

badboy24