如何正确转换堆栈图 chartJS 的数据(数据转换)?
How to correctly transform data for a stack chart chartJS (data transformation)?
有来自服务器的数据
const groupedChartData = [
{
duration: '00:00:10',
stats: [
{color: 'red', reason: 'yes', value: 11},
{color: 'green', reason: 'no', value: 33},
]
},
{
duration: '00:01:00',
stats: [
{color: 'black', reason: 'call back', value: 32},
{color: 'green', reason: 'no', value: 77},
]
},
{
duration: '00:10:00',
stats: [
{color: 'red', reason: 'yes', value: 14},
]
}
]
根据服务器的数据,需要生成如下对象才能正确显示
图表上的数据,即 groupedChartData 中 stats 对象的每个第一个值必须对应
到下一个对象中的第一个,第二个到第二个,并且
预测结果
let result = [
{
data: [11, 32, 14],
backgroundColor: ['red', 'black', 'red']
},
{
data: [33,77],
backgroundColor: ['green', 'green']
}
]
希望下面的注释代码对您有所帮助:
const result = []
groupedChartData.forEach(el=>{
el.stats.forEach((el, ind)=>{
//checking if position is null
if(result[ind] == null){
result[ind] = {data:[], backgroundColor: []}
}
//pushing new values to the new array
result[ind].data.push(el.value)
result[ind].backgroundColor.push(el.color)
})
})
console.log(result)
有来自服务器的数据
const groupedChartData = [
{
duration: '00:00:10',
stats: [
{color: 'red', reason: 'yes', value: 11},
{color: 'green', reason: 'no', value: 33},
]
},
{
duration: '00:01:00',
stats: [
{color: 'black', reason: 'call back', value: 32},
{color: 'green', reason: 'no', value: 77},
]
},
{
duration: '00:10:00',
stats: [
{color: 'red', reason: 'yes', value: 14},
]
}
]
根据服务器的数据,需要生成如下对象才能正确显示
图表上的数据,即 groupedChartData 中 stats 对象的每个第一个值必须对应
到下一个对象中的第一个,第二个到第二个,并且
预测结果
let result = [
{
data: [11, 32, 14],
backgroundColor: ['red', 'black', 'red']
},
{
data: [33,77],
backgroundColor: ['green', 'green']
}
]
希望下面的注释代码对您有所帮助:
const result = []
groupedChartData.forEach(el=>{
el.stats.forEach((el, ind)=>{
//checking if position is null
if(result[ind] == null){
result[ind] = {data:[], backgroundColor: []}
}
//pushing new values to the new array
result[ind].data.push(el.value)
result[ind].backgroundColor.push(el.color)
})
})
console.log(result)