ChartJS 如何对JSON数据数组进行分组和求和[已关闭]

axr492tv  于 2022-12-18  发布在  Chart.js
关注(0)|答案(2)|浏览(136)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
4天前关闭。
Improve this question
我有这样的数据

const
  timeStamp = 
    [ '2022-12-01', '2022-12-01'
    , '2022-12-02', '2022-12-02'
    , '2022-12-03', '2022-12-03', '2022-12-03' 
    ]
, stroke = [ '1', '0', '0', '0', '1', '0', '0' ]
, tbi =    [ '0', '1', '1', '1', '0', '0', '1' ]
, sci =    [ '0', '0', '0', '0', '0', '1', '0' ]

我想创建如下所示的新jsdata以创建图表Js

const jsDataFinal = 
  [ { timeStamp : '2022-12-01'
    , dxGroup   : { "stroke ": "1", "tbi ": "1", "sci ": "0" } 
    }
  , { timeStamp : '2022-12-02'
    , dxGroup   : { "stroke ": "0", "tbi ": "2", "sci ": "0" }
    }
  , { timeStamp : '2022-12-03'
    , dxGroup   : { "stroke ": "1", "tbi ": "1", "sci ": "1" } 
    } 
  ]

我尝试了很多次,我想从我的谷歌表创建图表js

y4ekin9u

y4ekin9u1#

在这种情况下,下面的示例脚本如何?

示例脚本:

const timeStamp = ['2022-12-01', '2022-12-01', '2022-12-02', '2022-12-02', '2022-12-03', '2022-12-03', '2022-12-03'];
const stroke = ['1', '0', '0', '0', '1', '0', '0'];
const tbi = ['0', '1', '1', '1', '0', '0', '1'];
const sci = ['0', '0', '0', '0', '0', '1', '0'];

const res = [...timeStamp.reduce((m, e, i) => {
  const o = m.get(e);
  const v1 = Number(stroke[i]) + (o?.dxGroup.stroke ? Number(o.dxGroup.stroke) : 0);
  const v2 = Number(tbi[i]) + (o?.dxGroup.tbi ? Number(o.dxGroup.tbi) : 0);
  const v3 = Number(sci[i]) + (o?.dxGroup.sci ? Number(o.dxGroup.sci) : 0);
  return m.set(e, { timeStamp: e, dxGroup: { stroke: v1.toString(), tbi: v2.toString(), sci: v3.toString() } });
}, new Map()).values()];
console.log(res);

测试:

运行此脚本时,将获得以下结果。

[
  { "timeStamp": "2022-12-01", "dxGroup": { "stroke": "1", "tbi": "1", "sci": "0" } },
  { "timeStamp": "2022-12-02", "dxGroup": { "stroke": "0", "tbi": "2", "sci": "0" } },
  { "timeStamp": "2022-12-03", "dxGroup": { "stroke": "1", "tbi": "1", "sci": "1" } }
]

参考:

oyxsuwqo

oyxsuwqo2#

你可以试试这个

const timeStamp = [  '2022-12-01', '2022-12-01', '2022-12-02', '2022-12-02', '2022-12-03', '2022-12-03', '2022-12-03'  ]

    const stroke = [ '1', '0', '0', '0', '1', '0', '0' ]
    const tbi =    [ '0', '1', '1', '1', '0', '0', '1' ]
    const sci =    [ '0', '0', '0', '0', '0', '1', '0' ]


    //Format Data

    let result =[];

    timeStamp?.forEach((item, index) => {
      let resultObj = {timeStamp:item}
      let dxGroup = {stroke: stroke[index], tbi: tbi[index], sci:sci[index]}
      resultObj = {...resultObj, dxGroup}

      result.push(resultObj)
    })

    console.log(result)

相关问题