12

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?

3
  • @OwaisAslam, this is definitely not a duplicate of that question. Both involve mapping objects and arrays, and similar tools, but they have very different starting and ending shapes Commented Jun 29, 2020 at 23:39
  • @KyleMit What did I say? Commented Jul 2, 2020 at 5:18
  • oh, it was just a duplicate suggestion - sorry for the lack of context - i also flagged the comment as no longer necessary (no penalties to authors for that) so I guess it's since been removed - i'll remove this and my original comment Commented Jul 2, 2020 at 17:15

5 Answers 5

22

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:

Sign up to request clarification or add additional context in comments.

Comments

3

Assuming your object instance is named obj:

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

Comments

1

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

Comments

1

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.

Comments

0

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)

2 Comments

The map method is used to project new values from the current ones and return the result. You should be using .forEach() instead.
can you explain in more details why should be use forEach instead of map method

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.