循环访问JSON并提取数组/描述,需要帮助

时间:2013-01-15 17:26:08

标签: jquery arrays json loops

[
{
    "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,我如何遍历每个JSON,并在jquery / javascript中分配包含描述的两个变量和ChartData的数组,即

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

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

1 个答案:

答案 0 :(得分: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/