如何在jQuery中迭代此JSON对象? [英] How do I iterate through this JSON object in jQuery?

查看:72
本文介绍了如何在jQuery中迭代此JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由PHP生成的JSON对象.这是带有一组日期的对象.它具有timeStamp,然后是日期的格式化版本.我将如何在jQuery中进行迭代?

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"
    }
  ]
}

我尝试过:

for (var i in data) { 
  alert(data.dates[i].timeStamp); 
};

for (var i in data) { 
  alert(data[i].dates.timeStamp); 
};

for (var i in data) { 
  alert(data.dates.timeStamp[i]); 
};

推荐答案

由于您将问题标记为jquery,因此您应该使用

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

如果您要坚持使用 for in 语法(我认为您已经尝试过),一种解决方案可能是:

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

但是请注意,for in语法可能会做得比您想像的要多:还会对从原型继承的属性进行迭代,因此确保仅对对象实例属性进行迭代可能很有用:

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

更新
另一种优雅的方法是使用 Object.keys 方法,该方法返回一个包含目标对象中所有键的数组,以迭代该对象的所有属性:

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

这篇关于如何在jQuery中迭代此JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆