Advertisement
Advertisement


How to fetch values from object?


Question

I have an object which was deserialized from JSON:

[Log] {"Rob7":{"lastSeenAt":null,"state":"online","userId":"Rob7"},"Techyudh_rob63":{"lastSeenAt":"2018-07-18T17:45:56Z","state":"offline","userId":"Techyudh_rob63"},"Teacher4":{"lastSeenAt":null,"state":"online","userId":"Teacher4"}} (chat, line 965)

I want to fetch the state of each user from it. I am trying this.

var j = (JSON.stringify(val.presenceStore.store));
var json = $.parseJSON(j);
$(json).each(function(i, val) {
  $.each(val, function(k, v) { 
    console.log(k + " : " + v);
  });
});

However, it shows, Rob7: [object Object]. I am new with JSON. Can anyone please help?

2018/07/20
1
1
7/20/2018 8:51:55 AM

Accepted Answer

You can do that in plain JavaScript, no need of jQuery. After parsing the JSON, just loop over the returned value using Object.entries( ... ).forEach and you are set.

var data = {
  "Rob7": {
    "lastSeenAt": null,
    "state": "online",
    "userId": "Rob7"
  },
  "Techyudh_rob63": {
    "lastSeenAt": "2018-07-18T17:45:56Z",
    "state": "offline",
    "userId": "Techyudh_rob63"
  },
  "Teacher4": {
    "lastSeenAt": null,
    "state": "online",
    "userId": "Teacher4"
  }
};

Object.entries(data).forEach(([k, v]) => {
  console.log(k, v.state);
});

2018/07/20
1
7/20/2018 8:35:05 AM

Your problem here is that you are trying to append an object to a string in the line:

console.log(k + " : " + v);

The object inside v can't be appended as a string to the console so that's why you got : Rob7: [object Object]

Solution:

If you just separate the key and value logging statements it will work perfectly:

console.log(k + " : ");
console.log(v);

Another option is to get back a string from the v object, using JSON.stringify():

console.log(k + " : " + JSON.stringify(v));
2018/07/20