关于javascript:迭代JSON-Object

Iterating over a JSON-Object

本问题已经有最佳答案,请猛点这里访问。

我有以下JSON文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
{"Mensaplan": [{
       "Montag": [
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false},
            {"food":"Schnitzl","price":"5.00 €","vegetarian": true,"bio": false},
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false}
        ],

       "Dienstag": [
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false},
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": true},
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false}
        ],

       "Mittwoch": [
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false},
            {"food":"Schnitzl","price":"5.00 €","vegetarian": true,"bio": false},
            {"food":"Schnitzl","price":"4.00 €","vegetarian": false,"bio": true}
        ],

       "Donnerstag": [
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false},
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false},
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false}
        ],

       "Freitag": [
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false},
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false},
            {"food":"Schnitzl","price":"5.00 €","vegetarian": false,"bio": false}
        ]
    }]
}

我想重复一遍"mensaplan",然后每天获取("montag"、"dienstag"、"…"(德语))。我试图用jquery方法$.each来实现这一点,但是我不知道如何为这些天建立一个通配符,因为每个通配符都有不同的名称。

有人能帮我处理这件事吗?

提前感谢!


不需要jquery,简单的for…in循环就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var obj = JSON.parse(yourJsonString);

//for each object in the"Mensaplan" array
for(var i = 0; i < obj.Mensaplan.length; ++i) {

    //for each key in the object
    for(var key in obj.Mensaplan[i]) {

        var day = obj.Mensaplan[i][key];

        //here key is the day's name, and day is the data...

    }

}

希望这有帮助。


首先使用JSON进行解析。

var json = JSON.parse(jsonString)

那只是一个javascript对象。你应该用……

1
2
3
Object.keys(json).forEach(function (key) {
    json[key];  
});

如果使用for in,则需要检查对象是否具有该属性,并且不是其父母之一(if (json.hasOwnProperty) { //code here })。

使用object.keys不需要这样做,因为只获取对象拥有的键。


这里不需要jquery,只需简单的for-in就足够了,但是您必须检查hasownproperty函数,因为for-in循环还可以检索对象的方法。

1
2
3
4
5
for (var key in Mensaplan) {
    if (Mensaplan.hasOwnProperty(key) {
        console.log(Mensaplan[key]);
    }
}

更新:在您的例子中,mensaplan是一个包含在JSON中的数组…对于数组,最快的方法是循环的标准方法,而不是

4


1
2
3
4
5
var mensaplan = json['Mensaplan'];
for (key in mensaplan) {
     values = mensaplan[key];
     //do something with the values
}