1

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?

0

2 Answers 2

8

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

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

1 Comment

I gotta say. This is a very clean and elegant solution.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.