score:2

I've create a class for you, so you can use it anywhere:

HighChartObject = function (obj) {
    if (typeof obj === 'string') obj = JSON.parse(obj);

    for (var key in obj) {
        this[key] = obj[key];
    }
}

HighChartObject.prototype.getDataArray = function () {
    var arr = [];

    for (var key in this) {
        if (this.hasOwnProperty(key)) {
            arr.push(obj[key]);
        }
    }

    return arr;
}

HighChartObject.prototype.getCategoriesArray = function () {
    var arr = [];

    for (var key in this) {
        if (this.hasOwnProperty(key)) {
            arr.push(key);
        }
    }

    return arr;
}

Usage:

var json = '{ "A": 5, "B": 12, "C": 5, "D": 11, "E": 6 }';
var obj = new HighChartObject(json);

$("#container").highcharts({
    xAxis: {
        categories: obj.getCategoriesArray()
    },
    series: [
        {
            name: "MyName",
            data: obj.getDataArray()
        }
    ]
});

And here there is a FIDDLE, so you can play with it!

I don't know if this is exactly what you need, but I think you can improve the code for your needs, right?

I hope it can help you =)


Related Articles