繁体   English   中英

JavaScript循环遍历JSON数组?

[英]JavaScript loop through JSON array?

我正在尝试遍历以下 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 应如下所示:

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

您的代码中有一些问题,首先您的 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/

尝试这个

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

因为我已经开始研究它:

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指出的那样,数组的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

链接

这是工作。 我只是在 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);
   }
} 

您的数据片段需要扩展一点,并且必须以这种方式成为正确的 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];
}

如果要迭代它,它必须是一个数组。 您很可能缺少[]

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/

好吧,我只能看到你有两个 JSON 对象,用逗号分隔。 如果它们都在一个数组( [...] )内,那将更有意义。

而且,如果它们在数组内,那么您将只使用标准的“for var i = 0 ...”类型的循环。 事实上,我认为它将尝试检索字符串“1”的“id”属性,然后检索“hi”的“id”,等等。

有点晚了,但我希望我可以帮助别人: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]);
            }
       }
}

非常简单的方法!

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

谢谢你。

var json = {
    "persons": [
        {"name": "Lili", "age": 23, "is_student": true},
        {"name": "James", "age": 24, "is_student": true},
        {"name": "John", "age": 25, "is_student": false}
    ]
};

for (var key in json.persons) {
    for (var keyName in json.persons[key]) {
        alert(keyName + ': ' + (json.persons[key])[keyName]);
    }
}

//输出:name:Lili, age:23, is_student:true, ...

使用map箭头函数的简短解决方案

 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" }]; data.map((item, i) => console.log('Index:', i, 'Id:', item.id));

并且要涵盖属性"id"不存在的情况,请使用filter

 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" }, { "msg": "abcde", "tid": "2013-06-06 23:46", "fromWho": "hello3@email.se" }]; data.filter(item=>item.hasOwnProperty('id')) .map((item, i) => console.log('Index:', i, 'Id:', item.id));

您可以使用 for 循环然后获取可以解构它们的值

const arr = [
        {
            id:123,
            desc:"do something",
            isDone:false
        },
        {
            id:124,
            desc:"do something",
            isDone:true
        }
    ]

for(let _i in arr){
    let {id, desc, isDone} = arr[_i]
    // do something
    console.log({id, desc, isDone});
}


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM