Loop over a JSON object containing an array of objects
really hope someone can help me with this, it's driving me mad now...
I have a JSON object, with source:
[{"description":"General Accessories & Parts","id":"1"},{"description":"General Parts","id":"2"},{"description":"Parts","id":"3"}]
It's an array returned from PHP, it used to look like this:
$array[0]['description']="General Accessories & Parts";
$array[0]['id']="1";
$array[1]['description']="General Parts";
$array[1]['id']="2";
etc...
So, I put the array into my JavaScript code:
obj=eval(ajax.responseText);
Now 开发者_开发技巧I need to loop over the description and id for each element in the array, I did try this:
for(var key in obj){
if(!obj[key].hasOwnProperty(key)) continue;
alert(obj[key]['description']);
}
The above code that I tried just echos [object Object],[object Object],[object Object]
which is the 3 objects that I know are there.
Use
alert( obj[0].description );
and not
alert( obj[0]['description'] );
Quick example: http://jsfiddle.net/W4dwx/
strange code: if(!obj[key].hasOwnProperty(key))
in your case, the key variable will iterate values 0, 1, 2
and you will ask for obj[0].hasOwnProperty(0)
I can't really duplicate your answer, but I'm pretty certain the issue is either a) in your response text (any chance we can get an alert of the exact output?) or b) in your for loop (you're iterating over an array, so it shouldn't have its own property):
var a = [{"description":"General Accessories & Parts","id":"1"},
{"description":"General Parts","id":"2"},
{"description":"Parts","id":"3"}];
var b = JSON.stringify(a);
eval("var c = " + b);
for (var i = 0; i < c.length; i++) {
alert(c[i].description); // alert the three values you want
}
精彩评论