简体   繁体   English

JavaScript循环遍历JSON数组?

[英]JavaScript loop through JSON array?

I am trying to loop through the following 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"
}

And have tried the following并尝试了以下

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

But for some reason I'm only getting the first part, id 1 values.但由于某种原因,我只得到第一部分,id 1 值。

Any ideas?有任何想法吗?

Your JSON should look like this:您的 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"
}];

You can loop over the Array like this:您可以像这样循环数组:

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

    console.log(obj.id);
}

Or like this (suggested from Eric) be careful with IE support或者像这样(由 Eric 建议)小心 IE 支持

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

There's a few problems in your code, first your json must look like :您的代码中有一些问题,首先您的 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"
}];

Next, you can iterate like this :接下来,您可以像这样迭代:

for (var key in json) {
if (json.hasOwnProperty(key)) {
  alert(json[key].id);
  alert(json[key].msg);
}
}

And it gives perfect result.它给出了完美的结果。

See the fiddle here : http://jsfiddle.net/zrSmp/在这里查看小提琴:http: //jsfiddle.net/zrSmp/

try this尝试这个

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 method for easy implementation. 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);
});

Since i already started looking into it:因为我已经开始研究它:

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

And this function而这个功能

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

You can call it like this你可以这样称呼它

iterateData(data); // write 1 and 2 to the console

Update after Erics comment埃里克评论后更新

As eric pointed out a for in loop for an array can have unexpected results .正如eric指出的那样,数组的for in循环可能会产生意想不到的结果 The referenced question has a lengthy discussion about pros and cons.引用的问题对利弊进行了冗长的讨论。

Test with for(var i ...用 for(var i ...

But it seems that the follwing is quite save:但似乎以下内容非常节省:

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

Although a test in chrome had the following result虽然 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); 

Test with .forEach()使用.forEach()进行测试

At least in chrome 30 this works as expected至少在 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

Links链接

It is working.这是工作。 I just added square brackets to JSON data.我只是在 JSON 数据中添加了方括号。 The data is:数据是:

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

And the loop is:循环是:

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

Your data snippet need to be expanded a little, and it has to be this way to be proper JSON.您的数据片段需要扩展一点,并且必须以这种方式成为正确的 JSON。 Notice I just include the array name attribute item .请注意,我只包含数组名称属性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"
  }]
}

Your JavaScript is simply你的 JavaScript 很简单

var objCount = json.item.length;
for (var x = 0; x < objCount; x++) {
  var curitem = json.item[x];
}

It must be an array if you want to iterate over it.如果要迭代它,它必须是一个数组。 You're very likely missing [ and ] .您很可能缺少[]

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

Check out this jsfiddle: http://jsfiddle.net/lpiepiora/kN7yZ/看看这个 jsfiddle:http: //jsfiddle.net/lpiepiora/kN7yZ/

Well, all I can see there is that you have two JSON objects, seperated by a comma.好吧,我只能看到你有两个 JSON 对象,用逗号分隔。 If both of them were inside an array ( [...] ) it would make more sense.如果它们都在一个数组( [...] )内,那将更有意义。

And, if they ARE inside of an array, then you would just be using the standard "for var i = 0..." type of loop.而且,如果它们在数组内,那么您将只使用标准的“for var i = 0 ...”类型的循环。 As it is, I think it's going to try to retrieve the "id" property of the string "1", then "id" of "hi", and so on.事实上,我认为它将尝试检索字符串“1”的“id”属性,然后检索“hi”的“id”,等等。

A bit late but i hope i may help others :D有点晚了,但我希望我可以帮助别人:D

your json needs to look like something Niklas already said.你的 json 需要看起来像 Niklas 已经说过的。 And then here you go:然后你去:

for(var key in currentObject){
        if(currentObject.hasOwnProperty(key)) {
          console.info(key + ': ' + currentObject[key]);
        }
   }

if you have an Multidimensional array, this is your code:如果你有一个多维数组,这是你的代码:

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

the very easy way!非常简单的方法!

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

Thank you.谢谢你。

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

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

A short solution using map and an arrow function使用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));

And to cover the cases when the property "id" is not present use filter :并且要涵盖属性"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));

you can use a for-loop then to get the values you can De-structure them您可以使用 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