user1935987 user1935987 - 5 months ago 8
JSON Question

parse values from javascript object

I see there is a problem to get a String name from JSON object's name.
I need to parse this kind on JSON response from server.

var response = {
hopaopGmailsjIpW: {
GmailsjIpW_totalEmails_count: 133,
GmailsjIpW_state: 1
},
hopaopGmail4y4yu: {
Gmail4y4yu_totalEmails_count: 156,
Gmail4y4yu_state: 1
}
}


It is not an
Array
, but the object with inner objects.
i need to parse an inner ojects name and add additional values to each object.

i want be able to do something like this:

for(var i =0; i < response.length; i++){
response[i].username = parseUsernameFromString(response[i]);
response[i].service = parseServiceFromString(response[i]);
response[i].id = parseIdString(response[i]);
}


(and also state for each task)

So the question is:
What is the best way to make it?

UPDATE
this is exactly what i have for now:

for(var key in response){
if(stringContains(response[key], "Gmail")) { response[key].service = "Gmail";}
console.log("task name: "+ response[key].service);
}
function stringContains(originalString, searchString){
if(originalString.indexOf(searchString) > -1){
return true
}
else return false;
}

Answer

For walking through Objects, you need to use for ... in loop.

The real problem is: There's a , missing in your code. See the fixed working snippet:

Snippet

var response_Parsed = {
  hopaopGmailsjIpW: {
    GmailsjIpW_totalEmails_count: 133,
    GmailsjIpW_state: 1,
    service: 'Gmail',
    username: 'hopaop',
    id: 'sjIpW'
  },
  hopaopGmail4y4yu: {
    Gmail4y4yu_totalEmails_count: 156,
    Gmail4y4yu_state: 1,
    service: 'Gmail',
    username: 'hopaop',
    id: '4y4yu'
  }
};
for (id in response_Parsed) {
  console.log("----");
  if (id.indexOf("Gmail") > -1) {
    console.log("We have Gmail: " + id);
    console.log("UniqueName:    " + id.replace("hopaopGmail", ""));
    console.log("Username:      " + response_Parsed[id].username);
    console.log("Email Count:   " + response_Parsed[id][id.replace("hopaop", "") + "_totalEmails_count"]);
  }
  else
    console.log("We don't have Gmail: " + id);
}

And also the right way to enumerate the through the keys of the objects, is by using Object.keys.

Comments