从JSON填充Highchart列

时间:2015-01-21 07:42:58

标签: javascript ajax json highcharts

我必须使用Highchart在项目中创建柱形图。我使用$ .ajax来填充这些数据。我当前的JSON数据是这样的:

[{
    "city": "Tokyo",
    "totalA": "10",
    "totalB": "15"
},
{
    "city": "Seoul",
    "totalA": "20",
    "totalB": "27"
},
{
    "city": "New York",
    "totalA": "29",
    "totalB": "50"
}]

如何使JSON字符串看起来像这样:

[{
"name": "city",
"data": ["Tokyo", "Seoul", "New York"]
}, {
"name": "totalA",
"data": [10, 20, 29]
}, {
"name": "totalB",
"data": [15, 27, 50]
}]

谢谢。

1 个答案:

答案 0 :(得分:1)

假设所有元素看起来都一样(它们都有相同的字段):Live Example

// src is the source array
// Get the fields from the first element
var fields = Object.keys(src[0]);

// Map each key to...
var result = fields.map(function(field) {
    // Grab data from the original source array
    var data = src.reduce(function(result, el) {
        // And create an array of data
        return result.concat(el[field]);
    }, []);
    // Format it like you want
    return {name: field, data: data};
});

console.log(result);

如果不是,则代码稍微复杂一些:Live Example

// Work out the fields by iterating all of the elements
// and adding the keys that weren't found yet to an array
var fields = src.reduce(function (fields, current) {
    return fields.concat(Object.keys(current).filter(function (key) {
        return fields.indexOf(key) === -1;
    }));
}, []);

var result = fields.map(function (field) {
    // Need another step here, filter out the elements
    // which don't have the field we care about
    var data = src.filter(function (el) {
        return !!el[field];
    })
    // Then continue like in the example above.
    .reduce(function (result, el) {
        return result.concat(el[field]);
    }, []);
    return {
        name: field,
        data: data
    };
});

console.log(result);