Q:

How to access key in a nested object

{
  "5def224170a3ec0d90dbb89a": {
    "_id": "5def224170a3ec0d90dbb89a",
    "username": "dhruv1999",
    "fullname": "dhruv parmar",
    "email": "dhruv@gmail.com",
    "phone": "7045691556",
    "password": "$2a$10$UOk8E4fbkkZvSRSzQqWK4eyJ2Z.qtL4D38thfhzkxJ1pSxSFn5fna",
    "__v": 0
  },
  "5def2747d135311a747a9660": {
    "_id": "5def2747d135311a747a9660",
    "username": "dhruv1998",
    "fullname": "parmar",
    "email": "dhruvkp@gmail.com",
    "phone": "704591556",
    "password": "$2a$10$px5SK.OpP7i2Ryvg.ko/OeIbuq9XDT3luTrIBloNFCTiImUJC1BIm",
    "__v": 0
  }
}

How can i get all the email such as dhruv@gmail.com, dhruvkp@gmail.com
I tried doing but not getting the email.
const userMap = {};
users.forEach(user => {
  userMap[user._id] = user;
});

userMap.forEach((obj) => {
      keys = Object.keys(obj);
      keys.forEach((key) => {
        console.log(obj[key].email);

      });

A:

The reason why the following doesn't work is because userMap is an object (you're also not closing your outer .forEach loop, which will be a syntax error) :
userMap.forEach((obj) => {
  keys = Object.keys(obj);
  keys.forEach((key)=>{
    console.log(obj[key].email);
  });

In order to use .forEach(), you need to use it on an array (or an array-like collection). Instead, you can get the Object.values() of your object. Object.values() gives back an array, so you can then use .map() on it to get the email properties:

const obj = {"5def224170a3ec0d90dbb89a": { "_id": "5def224170a3ec0d90dbb89a", "username": "dhruv1999", "fullname": "dhruv parmar", "email": "dhruv@gmail.com", "phone": "7045691556", "password": "$2a$10$UOk8E4fbkkZvSRSzQqWK4eyJ2Z.qtL4D38thfhzkxJ1pSxSFn5fna", "__v": 0 }, "5def2747d135311a747a9660": { "_id": "5def2747d135311a747a9660", "username": "dhruv1998", "fullname": "parmar", "email": "dhruvkp@gmail.com", "phone": "704591556", "password": "$2a$10$px5SK.OpP7i2Ryvg.ko/OeIbuq9XDT3luTrIBloNFCTiImUJC1BIm", "__v": 0 } }

const res = Object.values(obj).map(({email}) => email);
console.log(res);
console.log(res.join(', ')); // use `.join()` for string output

