按月动态数据集



我正在尝试为我的图表创建月份数据数组。合并每个月的所有销售和购买价值

谁能帮助我获得预期的产出,真的会很有帮助。我已经附上了小提琴,我试着用我的预期输出来创建图表

如果可能的话,用一些对我有用的java脚本函数来指导我

http://jsfiddle.net/qjsgy6a6/2/

var mainData = [
{
"date": "2017-01-03",
"month": "JAN",
"sales": "200",
"purchase": "1000"
},
{
"date": "2017-01-18",
"month": "JAN",
"sales": "800",
"purchase": "2500"
},
{
"date": "2017-01-22",
"month": "JAN",
"sales": "400",
"purchase": "2100"
},
{
"date": "2017-02-20",
"month": "FEB",
"sales": "40",
"purchase": "90"
},
{
"date": "2017-02-28",
"month": "FEB",
"sales": "970",
"purchase": "2100"
},
{
"date": "2017-02-29",
"month": "FEB",
"sales": "3300",
"purchase": "2900"
},
{
"date": "2017-03-20",
"month": "MAR",
"sales": "600",
"purchase": "900"
}
]

// Expected Output - how can I achieve this
{
"data": [
{
"data": [
{
"event": "sales",
"inventory": [
{
"value": "200"   //Jan
},
{
"value": "40"   //Feb
},
{
"value": "600"  //Mar
}
]
},
{
"event": "purchase",
"inventory": [
{
"value": "1000"
},
{
"value": "90"
},
{
"value": "900"
}
]
}
]
},
{
"data": [
{
"event": "sales",
"inventory": [
{
"value": "800"
},
{
"value": "970"
}
]
},
{
"event": "purchase",
"inventory": [
{
"value": "2500"
},
{
"value": "2100"
}
]
}
]
},
{
"data": [
{
"event": "sales",
"inventory": [
{
"value": "400"
},
{
"value": "3300"
}
]
},
{
"event": "purchase",
"inventory": [
{
"value": "2100"
},
{
"value": "2900"
}
]
}
]
}
]
}

您可以使用以下函数:

function transformData(data) {
return {
data: data.reduce ( (acc, item) => {
let i = acc.months.get(item.month) || 0;
acc.data[i] = acc.data[i] || {
data: [{
event: "sales",
inventory: []
}, {
event: "purchase",
inventory: []
}]
};
acc.data[i].data[0].inventory.push({ value: item.sales });
acc.data[i].data[1].inventory.push({ value: item.purchase });
acc.months.set(item.month, i+1);
return acc;
}, { months: new Map, data: [] } ).data
};
}
// Input
var data = [
{
"date": "2017-01-03",
"month": "JAN",
"sales": "200",
"purchase": "1000"
},
{
"date": "2017-01-18",
"month": "JAN",
"sales": "800",
"purchase": "2500"
},
{
"date": "2017-01-22",
"month": "JAN",
"sales": "400",
"purchase": "2100"
},
{
"date": "2017-02-20",
"month": "FEB",
"sales": "40",
"purchase": "90"
},
{
"date": "2017-02-28",
"month": "FEB",
"sales": "970",
"purchase": "2100"
},
{
"date": "2017-02-29",
"month": "FEB",
"sales": "3300",
"purchase": "2900"
},
{
"date": "2017-03-20",
"month": "MAR",
"sales": "600",
"purchase": "900"
}
];
// Conversion
var result = transformData(data);
// Output
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新