Filling the gaps in D3 array nesting

后端 未结 1 1118
时光取名叫无心
时光取名叫无心 2021-02-20 09:57

I have an array or objects consisting of a date and some values:

var flatData = [
    { \"date\": \"2012-05-26\", \"product\": \"apple\"  },
    { \"date\": \"20         


        
相关标签:
1条回答
  • 2021-02-20 10:26

    Try adding the missing data points after reduction:

    var flatData = [
        { "date": "2012-05-26", "product": "apple"  },
        { "date": "2012-07-03", "product": "orange" }]
    
    nestedData = d3.nest()
        .key(function(d) { return d.date.split('-')[0]; })  // key is the year
        .sortKeys(d3.ascending)
        .key(function(d) {
            var splitDate = d.date.split('-');
            return splitDate[0] + '-' + splitDate[1]; // key is year-month
        })
        .sortKeys(d3.ascending)
        .rollup(function(d) {
            return d.length;
        })
        .entries(flatData);
    
    
    yMFormat = d3.time.format('%Y-%m')
    
    makeAllKeys = function(year) {
        allKeys = [];
        for(var i = 0; i<12;i++) {  // 12 months in a year
            allKeys.push(yMFormat(new Date(year,i,1)));
        }
        return allKeys;
    }
    
    nestedData = nestedData.map(function(yearObj) {
        return {
            values: makeAllKeys(+yearObj.key).map(function(k) { 
                    value = yearObj.values.filter(function(v) { return v.key == k; })[0];
                    return value || ({key: k, values: 0});
                })
        };
    });
    
    0 讨论(0)
提交回复
热议问题