v-chart折线图数据改造
事件缘由
最近因为要做的项目当中需要用的折线图, 使用的框架中引用了v-chart, 可是因为后台返回的数据格式和 v-chart 所需的数据格式不同,出来的折线图和想象中的不一样,所以写了个转换的方法, 因此记录一下
// 后台返回的数据格式为
const retData = [
{
id: 1,
name: 'x',
dataList: [
{
creatDtm: '2019-08-27 10:00:00',
value: '31'
},
{
creatDtm: '2019-08-28 11:00:00',
value: '33'
},
{
creatDtm: '2019-08-29 12:00:00',
value: '35'
},
{
creatDtm: '2019-08-30 13:00:00',
value: '37'
}
]
},
{
id: 2,
name: 'y',
dataList: [
{
creatDtm: '2019-08-27 10:00:00',
value: '20'
},
{
creatDtm: '2019-08-28 11:00:00',
value: '22'
},
{
creatDtm: '2019-08-29 12:00:00',
value: '24'
},
{
creatDtm: '2019-08-30 13:00:00',
value: '26'
}
]
},
{
id: 3,
name: 'z',
dataList: [
{
creatDtm: '2019-08-27 10:00:00',
value: '41'
},
{
creatDtm: '2019-08-28 11:00:00',
value: '45'
},
{
creatDtm: '2019-08-29 12:00:00',
value: '44'
},
{
creatDtm: '2019-08-30 13:00:00',
value: '35'
}
]
}
]
-
而 v-chart 要求的数据格式是
-
感觉也不麻烦,所以先简单的做了一下操作
let columns = ['creatDtm'];
let rows = []
retData.map(i => {
columns.push(i.name)
let obj = {}
i.dataList.map(j => {
obj.createDtm = j.creatDtm
obj[i.name] = j.value
rows.push(obj)
})
})
console.log(rows)
结果是:
恩,很好很简单.搞定.
然而看折线图的时候有点傻眼,发现显示的不对劲…
莫名其妙多出来前面的空白日期 和 莫名其妙的x: 0 y: 0 z: 0
完全不是自己想要的样子…
后来才发现.原来 vchart 需要的数据格式是这样的
chartData: {
columns: ['日期', '销售额','下单率'],
rows: [
{ '日期': '1月1日', '销售额': 123, '下单率': 10% },
{ '日期': '1月2日', '销售额': 1223, '下单率': 10% },
{ '日期': '1月3日', '销售额': 2123, '下单率': 10% },
{ '日期': '1月4日', '销售额': 4123, '下单率': 10% },
{ '日期': '1月5日', '销售额': 3123, '下单率': 10% },
{ '日期': '1月6日', '销售额': 7123, '下单率': 10% }
]
}
…好吧,需要再次处理
let arr = []
rows.reduce(function(initArray,item){
let index = item.createDtm;
if(initArray[index]){
initArray[index].push(item)
}else{
let items = initArray[index]=[item]
arr.push(items)
}
return initArray;
},[])
let newRows = []
arr.map(i => {
if(i.length > 1) {
let obj = {}
i.map(j => {
obj = {...obj, ...j}
})
newRows.push(obj)
} else {
newRows.push(i[0])
}
})
console.log(newRows)
结果是:
效果:
搞定,收工