多层嵌套后D3重新格式化数据

时间:2018-11-30 19:39:58

标签: javascript d3.js

我试图按两列汇总数据,并保持原始JSON格式。使用Data aggregation in c3js的答案,我设法汇总了数据,但无法解决如何为多级嵌套修改答案“ //返回原始json格式”下面的部分。

下面是我到目前为止的代码和预期的输出。 我正在使用d3.js v3。

var json = [
    { name: 'name1', cat: 'hi', upload: 200, download: 200, total: 400 },
    { name: 'name1', cat: 'hello', upload: 200, download: 200, total: 400 },
    { name: 'name1', cat: 'hello', upload: 200, download: 200, total: 400 },
    { name: 'name1', cat: 'hi', upload: 100, download: 300, total: 400 },
    { name: 'name2', cat: 'hi', upload: 300, download: 200, total: 500 },
    { name: 'name2', cat: 'hello', upload: 300, download: 200, total: 500 },
    { name: 'name3', cat: 'hi', upload: 400, download: 100, total: 500 },
    { name: 'name3', cat: 'hi', upload: 400, download: 100, total: 500 },
    { name: 'name3', cat: 'hi', upload: 400, download: 100, total: 500 },
    { name: 'name3', cat: 'hi', upload: 400, download: 100, total: 500 },
    { name: 'name3', cat: 'hello', upload: 400, download: 100, total: 500 },
    { name: 'name3', cat: 'hello', upload: 400, download: 100, total: 500 },
];
var agg = function (json, nestField, nestField2) {
    var nested_data = d3.nest()
        .key(function (d) { return d[nestField]; })
        .key(function (d) { return d[nestField2]; })
        .rollup(function (leaves) {
            var keys = d3.merge(leaves.map(function (leaf) { return d3.keys(leaf); }));
            var keySet = d3.set(keys);
            keySet.remove(nestField);
            keySet.remove(nestField2);
            var dataFields = keySet.values()

            var obj = {};
            dataFields.forEach(function (dfield) {
                obj[dfield] = d3.sum(leaves, function (d) { return d[dfield]; });
            });
            return obj;
        })
        .entries(json);

        // return to original json format
        var final_data = nested_data.map (function(nestd) {
            nestd.values[nestField] = nestd.key;
            return nestd.values;
        });

        return final_data;

    return final_data;
};
var agg_data = agg(json, "name", "cat");
console.log(JSON.stringify(agg_data));

var desired_data = [
    { name: 'name1', cat: 'hi', upload: 300, download: 500, total: 800 },
    { name: 'name1', cat: 'hello', upload: 400, download: 400, total: 800 },
    { name: 'name2', cat: 'hi', upload: 300, download: 200, total: 500 },
    { name: 'name2', cat: 'hello', upload: 300, download: 200, total: 500 },
    { name: 'name3', cat: 'hi', upload: 1600, download: 400, total: 2000 },
    { name: 'name3', cat: 'hello', upload: 800, download: 200, total: 1000 },
];
console.log(JSON.stringify(desired_data));

0 个答案:

没有答案