JavaScript如何循环遍历JSON数组?

203

我正在尝试循环遍历以下 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的值。

有什么想法吗?


有一些括号丢失了吗?现在看起来并不像一个数组。你解析了JSON吗? - Denys Séguret
这是一个对象数组吗?(你是否缺少 [] 或者它们不存在?) - lpiepiora
9
既不是JSON也不是数组。 - JJJ
3
可能是JavaScript中遍历数组的重复问题 - Heretic Monkey
1
请更改标题,这是为了迭代JSON对象属性,而不是数组。 - Taylored Web Sites
14个回答

303

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

或者像这样(来自Eric的建议),注意IE的支持

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

17
更简洁地说,json.forEach(function(obj) { console.log(obj.id); }); 可以翻译为“遍历JSON对象并输出每个对象的ID属性值到控制台”。 - Eric
6
除了 IE8(像往常一样,除了 IE :)),其他浏览器都可以。 - lpiepiora
8
这个例子可能会让人感到困惑,因为变量json不是一个JSON对象,而是一个数组。在这种情况下,.forEach函数可以正常工作,但当您使用JSON对象时,它就不能正常工作了。 - Having a life on a beach

40

你的代码存在一些问题,首先你的json必须像这样:

var 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 json) {
if (json.hasOwnProperty(key)) {
  alert(json[key].id);
  alert(json[key].msg);
}
}

它给出了完美的结果。

在这里查看演示:http://jsfiddle.net/zrSmp/


36

试试这个

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

json.forEach((item) => {
  console.log('ID: ' + item.id);
  console.log('MSG: ' + item.msg);
  console.log('TID: ' + item.tid);
  console.log('FROMWHO: ' + item.fromWho);
});

19
var arr = [
  {
  "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"
  }
];

forEach 方法可方便实现。

arr.forEach(function(item){
  console.log('ID: ' + item.id);
  console.log('MSG: ' + item.msg);
  console.log('TID: ' + item.tid);
  console.log('FROMWHO: ' + item.fromWho);
});

13

既然我已经开始研究它:

var data = [{
    "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"
}]

而这个函数

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

你可以这样调用。
iterateData(data); // write 1 and 2 to the console

Eric的评论后更新

正如Eric所指出的那样,使用for in循环遍历数组可能会产生意外结果。参考问题中有关于利弊的长时间讨论。

使用for(var i ...)进行测试

但似乎以下方法相当安全:

for(var i = 0; i < array.length; i += 1)

尽管在Chrome中进行的测试得出以下结果
var ar = [];
ar[0] = "a"; 
ar[1] = "b";
ar[4] = "c";

function forInArray(ar){ 
     for(var i = 0; i < ar.length; i += 1) 
        console.log(ar[i]);
}

// calling the function
// returns a,b, undefined, undefined, c, undefined
forInArray(ar); 

使用.forEach()进行测试

至少在Chrome 30中,这个方法按预期工作。

var logAr = function(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
ar.forEach(logAr); // returns a[0] = a, a[1] = b, a[4] = c

链接


2
-1 - 不应该使用 for ... in 循环来遍历数组 - Eric
数组推导式使用 for eachfor ... in ... 是一种语言结构,用于按任意顺序枚举对象键。这不是一个适合数组的正确结构。 - Eric

10

它正在运作。我只是在JSON数据中添加了方括号。数据为:

var data = [
    { 
        "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)) {
         alert(data[key].id);
   }
} 

8

你的数据片段需要进行扩展,并且必须这样做才能生成正确的JSON格式。请注意,我只包含了数组名称属性item

{
  "item": [{
    "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"
  }]
}

您的JavaScript非常简单。
var objCount = json.item.length;
for (var x = 0; x < objCount; x++) {
  var curitem = json.item[x];
}

3
请注意,我认为有一个打字错误。xx++ 应该是 x++ - Jackie Johnston

7
如果您想迭代它,那么它必须是一个数组。您很可能缺少 []
var x = [{
    "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"
}];

var $output = $('#output');
for(var i = 0; i < x.length; i++) {
    console.log(x[i].id);
}

请查看此jsfiddle: http://jsfiddle.net/lpiepiora/kN7yZ/

6
有点晚了,但我希望我能帮到其他人 :D
你的JSON需要像Niklas已经说过的那样。然后就可以开始了:
for(var key in currentObject){
        if(currentObject.hasOwnProperty(key)) {
          console.info(key + ': ' + currentObject[key]);
        }
   }

如果你有一个多维数组,以下是你的代码:

for (var i = 0; i < multiDimensionalArray.length; i++) {
    var currentObject = multiDimensionalArray[i]
    for(var key in currentObject){
            if(currentObject.hasOwnProperty(key)) {
              console.info(key + ': ' + currentObject[key]);
            }
       }
}

5
非常容易的方法!
var tire_price_data = JSON.parse('[{"qty":"250.0000","price":"0.390000"},{"qty":"500.0000","price":"0.340000"},{"qty":"1000.0000","price":"0.290000"}]'); 
tire_price_data.forEach(function(obj){
    console.log(obj);
    console.log(obj.qty);
    console.log(obj.price);
})

谢谢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接