javascript - 如何正确转换堆栈图chartJS(数据转换)的数据?
问题描述
有来自服务器的数据
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对象的每个第一个值必须对应
next对象中的第一个,第二个到第二个, 和
预期结果
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)
推荐阅读
- python - 添加作为字符串传递的浮点数
- gcc - 我应该如何让 gcc 在进入函数的途中将堆栈指针重新对齐到 16 字节边界?
- python - 为什么我的 if 语句不起作用,只是输出 else,一切正常到那里?
- python-3.x - 遍历 2 个 Python 列表并获取所有 x 到 y 组合
- javascript - 我应该/我可以在 React 中组织数据吗?
- keycloak - 在 Keycloak 中,你可以使用 JWT 来获取调用者的身份吗?
- android - 如何在 Kotlin 中获得毕加索的听众
- python - 如何根据 django-rest-framework 中的最佳匹配对查询集进行排序?
- python - read_parquet Dask 中的 TypeError
- hazelcast - Hazelcast IMap.values() 和 IMap.values(Predicate) 给出不一致的值