1150 0 0 0
Last Updated : 2025-04-28 20:31:34
If you have a data object that is json encoded and need to iterate through the inner data objcets here are different suggestions
Let's assume we have this data structure
{
"dates":[
{
"timeStamp": 1317596400,
"formattedDate": "Mon 03 October 2011"
},
{
"timeStamp": 1317682800,
"formattedDate": "Tue 04 October 2011"
},
{
"timeStamp": 1317855600,
"formattedDate": "Thu 06 October 2011"
}
]
}
Now you can iterate through all the dates objects inside as follows:
$.each(data.dates, function(index, element) {
alert(element.timeStamp);
});
for(var key in data.dates) {
alert(data.dates[key].timeStamp);
}
/*
But beware that the for in syntax 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:
*/
for(var key in data.dates) {
// if it's not something from the prototype
if(data.dates.hasOwnProperty(key)) {
alert(data.dates[key].timeStamp);
}
}
/*
Another elegant way is to use the Object.keys method that returns an array containing all the keys in the targeted object to iterate over all the object's properties:
*/
for(var i=0, keys=Object.keys(data.dates), l=keys.length; i<l; i++) {
alert(data.dates[i].timeStamp);
}