用JavaScript将一个数组转换/转置为另一个数组?

问题描述 投票:0回答:1

我不是JavaScript开发人员,并且希望获得一些有关如何将对象数组(从WebAPI调用获取)转换为适合Chart.JS的数组的指针。

到目前为止,我的代码(有效)看起来像这样:

<canvas id="line-chart" width="800" height="450"></canvas>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<script>
    // webapi call returns an object which looks like this
    var raw = {
        message: "Success: 3 entries",
        didError: false,
        errorMessage: null,
        model:
        [
            { time: "2019-09-26T13:19:00", value1: 1, value2: 2, value3: 3, value4: 4 },
            { time: "2019-09-26T13:20:00", value1: 22, value2: 21, value3: 20, value4: 19 },
            { time: "2019-09-26T13:21:00", value1: 10, value2: 20, value3: 40, value4: 70 }
        ]
    };

    // chart.js needs the data to look like this
    var data = {
        labels: ["19:00", "20:00", "20:01"],
        datasets: [
            {
                data: [1, 22, 10],
                label: "Value 1",
                borderColor: "red",
                fill: false
            },
            {
                data: [2, 21, 20],
                label: "Value 2",
                borderColor: "blue",
                fill: false
            },
            {
                data: [3, 20, 40],
                label: "Value 3",
                borderColor: "green",
                fill: false
            },
            {
                data: [4, 19, 70],
                label: "Value 4",
                borderColor: "orange",
                fill: false
            }
        ]
    };

    var options = { title: { display: true, text: 'stuff' } };

    var chart = new Chart(document.getElementById("line-chart"), { type: 'line', data: data, options: options });

</script>

如何将“原始”数据转换为Chart.JS期望的格式?我可以使webAPI(我写的)返回任何内容,但不认为返回chart.js格式数组是可行的方法。当前返回1440个对象-不是3个!

我不了解js,所以我不知道如何进行循环和类型转换,因此所有指针都将不胜感激。如果可能的话,我宁愿不包括额外的软件包。

javascript chart.js
1个回答
0
投票

首先,您需要拆开模型数据:

const hashed = raw.model.reduce((acc, item) => {
  Object.keys(acc).forEach(k => acc[k].push(item[k]);
  return acc;
}, {
  value1: [],
  value2: [],
  value3: [],
  value4: [],
});

然后我们可以将其转换为chart.js的数据:

const chartData = Object.entries(hashed).map(([label, data]) => ({
  data,
  label,
  fill: false,
}));

仅剩下的是选择颜色(随机?如果不进行从标签到颜色的映射),然后格式化标签/键。

© www.soinside.com 2019 - 2024. All rights reserved.