Sandra Willford
Sandra Willford

Reputation: 3789

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?

Upvotes: 12

Views: 14854

Answers (5)

Ivar
Ivar

Reputation: 6857

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.

Upvotes: 1

sandeep sharma
sandeep sharma

Reputation: 11

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)

Upvotes: 0

SALEH
SALEH

Reputation: 1562

Assuming your object instance is named obj:

Object.keys(obj).reduce((acc, curr) => {
    return [...acc, { id: curr, name: obj[curr] }]
}, [])

Upvotes: 3

badboy24
badboy24

Reputation: 223

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]
    });
};

Upvotes: 1

Mohammad Usman
Mohammad Usman

Reputation: 39392

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:

Upvotes: 21

Related Questions