2
[
{
    "Description": "Accommodation",
    "ChartData": [
        {
            "label": "Acceptable",
            "data": 24
        },
        {
            "label": "Excellent",
            "data": 30
        },
        {
            "label": "Good",
            "data": 96
        },
        {
            "label": "Poor",
            "data": 2
        }
    ]
},    
{
    "Description": "Food and Beverage",
    "ChartData": [
        {
            "label": "Acceptable",
            "data": 44
        },
        {
            "label": "Excellent",
            "data": 24
        },
        {
            "label": "Good",
            "data": 94
        },
        {
            "label": "Poor",
            "data": 13
        }
    ]
},
{
    "Description": "Meeting Space",
    "ChartData": [
        {
            "label": "Acceptable",
            "data": 30
        },
        {
            "label": "Below Expectations",
            "data": 2
        },
        {
            "label": "Exceeds Expectations",
            "data": 3
        },
        {
            "label": "Excellent",
            "data": 54
        },
        {
            "label": "Good",
            "data": 111
        },
        {
            "label": "Meets Expectations",
            "data": 7
        },
        {
            "label": "Poor",
            "data": 6
        }
    ]
},    
{
    "Description": "Service",
    "ChartData": [
        {
            "label": "Acceptable",
            "data": 25
        },
        {
            "label": "Exceeds Expectations",
            "data": 3
        },
        {
            "label": "Excellent",
            "data": 46
        },
        {
            "label": "Good",
            "data": 111
        },
        {
            "label": "Meets Expectations",
            "data": 8
        },
        {
            "label": "Poor",
            "data": 11
        }
    ]
},
{
    "Description": "Standard of Decor",
    "ChartData": [
        {
            "label": "Acceptable",
            "data": 38
        },
        {
            "label": "Excellent",
            "data": 34
        },
        {
            "label": "Good",
            "data": 126
        },
        {
            "label": "Poor",
            "data": 5
        }
    ]
}
]

使用上面的 JSON,我如何循环遍历每个并分配两个包含描述的变量,以及 jquery/javascript 中 ChartData 的数组,即

foreach() {
var Description = data[].Description;
var ArrayOfChartData = data[].ChartData;
}

我尝试使用 .each 循环,但无法返回正确的数据。

4

1 回答 1

2

JavaScript 数组有一个forEach方法:

data.forEach(function (v) {
    var Description = v.Description;
    var ArrayOfChartData = v.ChartData;
    // now use that...
});

这是小提琴:http: //jsfiddle.net/u7RuZ/


不幸的是,IE < 9 不支持这一点。如果你必须支持 IE8,你可以使用 jQuery 的$.each

$.each(data, function (i, v) {
    var Description = v.Description;
    var ArrayOfChartData = v.ChartData;
    // now use that...
});

这是小提琴:http: //jsfiddle.net/u7RuZ/1/

于 2013-01-15T17:27:38.430 回答