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个回答

5
好的,我看到你有两个JSON对象,中间用逗号分隔。如果它们都在一个数组([...])中,就更有意义了。

如果它们确实在一个数组中,那么你只需要使用标准的“for var i = 0…”类型的循环即可。现在这样写会尝试获取字符串“1”的“id”属性,然后是“hi”的“id”,以此类推。


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

//输出:姓名:Lili,年龄:23岁,是否是学生:是,...


2

使用 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));


0
您可以使用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});
}



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