Loop through a json object data using javascript or jquery

1003 0 0 0

Last Updated : 2024-04-25 23:24:30

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:



  1. Suggestions #1
    $.each(data.dates, function(index, element) {
    alert(element.timeStamp);
    });​


  2. Suggestion #2
    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);
    }
    }


  3. Suggestion #3
    /*
    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);
    } ​


  4. Suggestion #4

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .