alex
alex

Reputation: 7601

How to turn this ID-based objects into an array of objects?

I have data like this:

{
  "-L8BpxbS70KYrZMQUF0W": {
    "createdAt": "2018-03-22T16:33:57+08:00",
    "email": "[email protected]",
    "name": "ss"
  },
  "-KYrZMQUF0WL8BpxbS70": {
     // etc.
   }
}

Which I want to turn into this:

[{
  id: '-L8BpxbS70KYrZMQUF0W
  createdAt: "2018-03-22T16:33:57+08:00",
  email: "[email protected]",
  name: "ss"
}, {
  id: -KYrZMQUF0WL8BpxbS70"
  // etc.
}]

I'm started with this:

  Object.keys(idBasedObjects).forEach(key => {
    console.log(resp[key])
  })

But I get undefined.

What's best way of creating this array?

Upvotes: 1

Views: 59

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

Get the keys and values using Object.entries(), and Array.map() them to to the required form using object spread:

const obj = {"-L8BpxbS70KYrZMQUF0W":{"createdAt":"2018-03-22T16:33:57+08:00","email":"[email protected]","name":"ss"},"-KYrZMQUF0WL8BpxbS70":{}};

const result = Object.entries(obj).map(([id, props]) => ({
  id,
  ...props
}));

console.log(result);

Upvotes: 8

gurvinder372
gurvinder372

Reputation: 68393

Use Object.keys, Object.assign and map

var output = Object.keys(obj).map( s => Object.assign( obj[s], {id : s} ))

Demo

var obj = {
  "-L8BpxbS70KYrZMQUF0W": {
    "createdAt": "2018-03-22T16:33:57+08:00",
    "email": "[email protected]",
    "name": "ss"
  },
  "-KYrZMQUF0WL8BpxbS70": {
    "createdAt": "2018-03-22T16:33:57+08:00",
    "email": "[email protected]",
    "name": "ss2"
  }
};

var output = Object.keys(obj).map(s => Object.assign(obj[s], {
  id: s
}));

console.log(output);

Upvotes: 2

Related Questions