在JavaScript中,如何将“长表格式”转换为适合折线图的数据结构:
var data = [
{"type":"A"," year":2000," value":50},
{"type":"A"," year":2001," value":51},
{"type":"A"," year":2002," value":52},
{"type":"B"," year":2000," value":60},
{"type":"B"," year":2001," value":55},
{"type":"B"," year":2002," value":57}
]
=>
var series = [
{type: "A", values : [{x: 2000, y: 50}, {x: 2001, y: 52},] },
{type: "B", values : [{x: 2000, y: 60}, {x: 2001, y: 55},] },
]
一个vanilla JavaScript解决方案以及一个Crossfilter库的解决方案 - 可以在任何数据维度上工作 - 很有价值: https://github.com/square/crossfilter/wiki/API-Reference
答案 0 :(得分:1)
好问题,但不是明确的; )
查看https://github.com/NickQiZhu/dc.js/pull/91
你会有类似的东西:
cr = crossfilter(data);
typeDim=cr.dimension(function(d) {return d.type});
typeGroup=typeDim.group();
yearDim=cr.dimension(function(d) {return d.year});
valDim=cr.dimension(function(d) {return d.value});
yearTypeGroup = dateDimension.group();
yearTypeGroup.reduce(
// add
// pivot[0].idx()[i] returns the index of statusGroup
// the reduce function hence construct a key-value object, keys being indexes of the pivot group.
function(p, v, i, pivot) {
++p[pivot[0].idx()[i]].count;
p[pivot[0].idx()[i]].value += +v.value;
return p;
},
//remove
function(p, v,i,pivot) {
--p[pivot[0].idx()[i]].count;
p[pivot[0].idx()[i]].value -= +v.value;
return p;
},
//init
function(pivot) {
var l, i, obj ={};
if(l = pivot[0].all().length){
for(i=0; i<l; ++i) {
obj[i] = {count:0, value:0}
}
}
return obj
}
);
yearTypeGroup.pivot(typeGroup)
祝你好运; )
下进行。