-3

I tried:

Object.keys(user).forEach(item => {
  console.log(item)
})

But response is simply 5

{
  "5": {
    "avatar": "https://reqres.in/img/faces/12-image.jpg",
    "banner": "https://via.placeholder.com/1500x500.png?text= Banner",
    "email": "rachel.howell@reqres.in",
    "id": 12,
    "links": {
      "fb": "https://www.facebook.com/",
      "ig": "https://www.facebook.com/",
      "twt": "https://www.facebook.com/",
      "yt": "https://www.facebook.com/"
    },
    "name": "Rachel Howell",
    "walletAddress": "howell111"

  }
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • 2
    `Object.keys()` will return an array of keys of the object. There's only one `'5'`. That's what you get. – evolutionxbox Jun 13 '21 at 15:50
  • 1
    Also please follow the advice you posted in the question... _"how about adding more details. Like, what are you trying to accomplish, how are you doing it, what difficulties you have found with the approach, another approaches you have tried, etc"_ – evolutionxbox Jun 13 '21 at 15:51
  • So Instead of 5 if I need to access "name" and its value how to do that ? Please suggest some javascript logic . Thanks in advance. – Creeper Jun 13 '21 at 15:59
  • 1
    No logic needed. Consider using object access notation: `user['5'].name`? – evolutionxbox Jun 13 '21 at 16:09

1 Answers1

0

So if you know it's going to be one level down, here is how you could list everything one level down:

Object.keys(user).forEach(item => {
  Object.keys(user[item]).forEach(innerItem =>{
    console.log(innerItem + ': ' + user[item][innerItem])

} ) })

If you know you want name then either you could adapt the above to have

if (innerItem == 'name'){ //or ===
  console.log(innerItem + ': ' + user[item][innerItem])}

or as evolutionxbox commented:

Object.keys(user).forEach(item => {

  console.log(user[item].name)}

)

On the other hand, if you want all simple properties, but you don't know how deep they will be, you can do the following adapted from traversing through JSON string to inner levels using recursive function

function scan(obj, propName) {
var k;
if (obj instanceof Object) {
    for (k in obj){
        if (obj.hasOwnProperty(k)){
            //recursive call to scan property
            scan( obj[k], k );  
        }                
    }
} else {
    //obj is not an instance of Object so obj here is a value
    console.log(propName+': '+ obj)
};

};

scan(user, 'top')

And if you know you want names only, block your console log as follows:

if (propName === 'name'){
    console.log(propName+': '+ obj)}
Jeremy Kahan
  • 3,796
  • 1
  • 10
  • 23