JavaScript循环遍历JSON数组?

新手上路,请多包涵

我正在尝试遍历以下 json 数组:

{
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "hello1@email.se"
}, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "hello2@email.se"
}

并尝试了以下

for (var key in data) {
   if (data.hasOwnProperty(key)) {
      console.log(data[key].id);
   }
}

但由于某种原因,我只得到第一部分,id 1 值。

有任何想法吗?

原文由 Alosyius 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 562
1 个回答

您的 JSON 应如下所示:

 let json = [{
    "id" : "1",
    "msg"   : "hi",
    "tid" : "2013-05-05 23:35",
    "fromWho": "hello1@email.se"
},
{
    "id" : "2",
    "msg"   : "there",
    "tid" : "2013-05-05 23:45",
    "fromWho": "hello2@email.se"
}];

您可以像这样遍历数组:

 for(let i = 0; i < json.length; i++) {
    let obj = json[i];

    console.log(obj.id);
}

或者像这样(埃里克建议)小心 IE 支持

json.forEach(function(obj) { console.log(obj.id); });

原文由 Niklas 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题