簡體   English   中英

如何正確轉換堆棧圖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']
  }
]

這種轉換對於我在chartJS中形成這種圖表是必要的。也許我做錯了什么,不需要如此復雜的轉換?無論如何,問題的本質是如何將我從服務器收到的 1 個結構帶到我在預期結果中描述的那個結構中

我希望下面的注釋代碼對您有所幫助:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM