How do I iterate through this JSON object in jQuery?

后端 未结 4 2124
自闭症患者
自闭症患者 2020-12-07 22:53

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 throu

相关标签:
4条回答
  • 2020-12-07 23:03

    You use $.each().
    It looks like this:

    $.each(data, function(n, elem) {
        // here you process your data to data loaded to lines               
    });
    
    0 讨论(0)
  • 2020-12-07 23:03

    You can simply iterate through the json structure using jQuery each:

    $.each(data, function(index, element) {
       alert(element.dates.timeStamp); 
    });
    
    0 讨论(0)
  • 2020-12-07 23:05

    jQuery.each() is probably the easiest way, check this out: http://api.jquery.com/jQuery.each/

    eg

    $.each(dates, function(index, date) { alert(date.timeStamp); });
    
    0 讨论(0)
  • 2020-12-07 23:11

    Since you tagged your question as a jquery one, you should use $.each because it's jquery's iterator function:

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

    If you want to stick to the for in syntax (which i see you've tried), a solution might be :

    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); 
        }
    } 
    

    update
    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);
    } 
    
    0 讨论(0)
提交回复
热议问题