使用JavaScript从表中为多系列FusionCharts创建DataSet

时间:2017-05-23 13:47:49

标签: javascript fusioncharts

我有一张表中的数据:

melt

我正在努力将代码转换为FusionCharts多系列图表所需的类别和数据集......结果应该是:

var my_data = [
{"series":"group1", "type":"device1", "value":15},
{"series":"group1", "type":"device3", "value":12},
{"series":"group2", "type":"device1", "value":16},
{"series":"group2", "type":"device1", "value":11},
{"series":"group2", "type":"device2", "value":17},
{"series":"group2", "type":"device2", "value":18},
{"series":"group2", "type":"device3", "value":10},
{"series":"group2", "type":"device4", "value":14},
{"series":"group3", "type":"device1", "value":13},
{"series":"group3", "type":"device3", "value":19},
{"series":"group3", "type":"device4", "value":11},
{"series":"group3", "type":"device4", "value":15}
];

挑战在于数据集顺序必须与类别匹配,并且数据值需要与每个类别的单个设备相加。

如何转换此数据?我假设第一步是使用for循环获取类别。但在那之后,我很难过。

这是工作图表,但手动转换数据: http://jsfiddle.net/yqqbqqe9/

1 个答案:

答案 0 :(得分:1)

您可以为类别创建一些辅助对象,并作为对同一系列的引用。然后为一个新系列构建一个具有全数零值的数组的对象。

至少将值添加到相应的对象。

此提案适用于未排序的数据,但首次出现的顺序构建了系列的顺序。如有必要,可以稍后对此进行分类。

var data = [{ series: "group1", type: "device1", value: 15 }, { series: "group1", type: "device3", value: 12 }, { series: "group2", type: "device1", value: 16 }, { series: "group2", type: "device1", value: 11 }, { series: "group2", type: "device2", value: 17 }, { series: "group2", type: "device2", value: 18 }, { series: "group2", type: "device3", value: 10 }, { series: "group2", type: "device4", value: 14 }, { series: "group3", type: "device1", value: 13 }, { series: "group3", type: "device3", value: 19 }, { series: "group3", type: "device4", value: 11 }, { series: "group3", type: "device4", value: 15 }],
    categories = [{ category: [{ label: "device1" }, { label: "device2" }, { label: "device3" }, { label: "device4" }] }],
    result = data.reduce(function (categories) {
        var catIndex = categories.reduce(function (r, o, i) {
                r[o.label] = i;
                return r;
            }, {}),
            series = Object.create(null);
            
        return function (r, o) {
            if (!series[o.series]) {
                series[o.series] = {
                    seriesname: o.series,
                    data: categories.map(function () { return { value: 0 } })
                };
                r.push(series[o.series]);
            }
            series[o.series].data[catIndex[o.type]].value += o.value;
            return r;
        };
    }(categories[0].category), []);


console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }