从 JSON 填充 Highchart 列

Populate Highchart Column From JSON

我必须使用 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]
}]

谢谢。

假设所有元素看起来都一样(它们都有相同的字段):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);