Mkhuda
Mkhuda

Reputation: 69

Populate Highchart Column From JSON

I have to create a column chart in my project using Highchart. I am using $.ajax to populate this data. My current JSON data is like this :

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

How to resulting JSON string look like this:

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

Thank you.

Upvotes: 0

Views: 136

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174957

Assuming all the elements look the same (they all have the same fields): 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);

If they aren't, the code is slightly more complicated: 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);

Upvotes: 1

Related Questions