简体   繁体   中英

How to correctly transform data for a stack chart chartJS (data transformation)?

There is data that comes from the server

  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},
      ]
    }
  ]

Based on the data from the server, you need to generate the following object for correct display data on the chart, that is, each first value from the stats object in groupedChartData must correspond
to the first in the next object, the second to the second, and

exprected result

let result = [
  {
    data: [11, 32, 14],
    backgroundColor: ['red', 'black', 'red']
  },
   {
    data: [33,77],
    backgroundColor: ['green', 'green']
  }
]

这种转换对于我在chartJS中形成这种图表是必要的。也许我做错了什么,不需要如此复杂的转换?无论如何,问题的本质是如何将我从服务器收到的 1 个结构带到我在预期结果中描述的那个结构中

I hope the commented code below helps you:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM