I have a JSON object which is generated by PHP. It’s an object with a set of dates. It has the timeStamp and then a formatted version of the date. How would I iterate through this in jQuery?
{
"dates":[
{
"timeStamp": 1317596400,
"formattedDate": "Mon 03 October 2011"
},
{
"timeStamp": 1317682800,
"formattedDate": "Tue 04 October 2011"
},
{
"timeStamp": 1317855600,
"formattedDate": "Thu 06 October 2011"
}
]
}
I’ve tried:
for (var i in data) {
alert(data.dates[i].timeStamp);
};
for (var i in data) {
alert(data[i].dates.timeStamp);
};
and
for (var i in data) {
alert(data.dates.timeStamp[i]);
};
Since you tagged your question as a
jqueryone, you should use$.eachbecause it’s jquery’s iterator function:If you want to stick to the
for insyntax (which i see you’ve tried), a solution might be :But beware that the
for insyntax may do more than you think it does: it iterates over the properties inherited from the prototype too, so it might be usefull to make sure you iterate only on the object instance properties:update
Another elegant way is to use the
Object.keysmethod that returns an array containing all the keys in the targeted object to iterate over all the object’s properties: