0

There's an API file I have in PHP, which returns votes in JSON like this:

[{"10002" : "-1"},{"10003" : "2"}]

Now, I basically need to be able to check the vote for each ID possibly in a for loop, like:

var parsed = JSON.parse(document.body.innerHTML); //[{"10002" : "-1"},{"10003" : "2"}] in string
for (i=0;i<parsed.length;i++) 
 {
     var toAlter = document.getElementById(parsed[i].something); //I need to retrieve the ID somehow
     toAlter.childNodes[2].innerHTML = parsed[i].something; //Need to retrieve the vote amount for the ID here
 }

1 Answers1

1

Try

var parsed = JSON.parse(document.body.innerHTML); //[{"10002" : "-1"},{"10003" : "2"}] in string
for (i=0;i<parsed.length;i++) {
    var obj = parsed[i];
    for(key in obj){
        if(obj.hasOwnProperty(key)){
            var toAlter = document.getElementById(key); //I need to retrieve the ID somehow
            toAlter.childNodes[2].innerHTML = obj[key]; //Need to retrieve the vote amount for the ID    here     
        }
    }

}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    Just a comment: obj.hasOwnProperty is overkill if you're dealing with JSON objects usually. In my usage, it's always much slower than using `obj[key] !== undefined`. – Mutahhir Jun 03 '13 at 12:11