Skip to content
Advertisement

How to transform an object into an array of objects?

I am looking for a way to transform an object into an array of objects, and remove the first unique key.

How can I make this:

{f56hdhgf54: {name: 'Sam', age: 34}, h65fg9f7d: {name: 'John', age: 42}}

into this:

[{name: 'Sam', age: 34}, {name: 'John', age: 42}]

so I can .map through it like this:

result.map((person) => {
   console.log(person.name, person.age)
})

Advertisement

Answer

You can use Object.keys() to get array of keys and then map() to change keys to values or in this case objects.

var obj = {f56hdhgf54: {name: 'Sam', age: 34}, h65fg9f7d: {name: 'John', age: 42}}

var result = Object.keys(obj).map(function(e) {
  return obj[e];
});

console.log(result);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement