Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
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']
  }
]

This transformation is necessary for me to form a chart of this kind in chartJS. Perhaps I am doing something wrong and such a complex transformation is not needed?
In any case, the essence of the question is how to bring 1 structure that I receive from the server to the one that I described in the expected result

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!