将数据结构分配给chartjs属性,而不是单独分配

时间:2019-03-15 22:20:26

标签: javascript charts chart.js visualization

考虑到chartjs网站[底部(http://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/#10-bubble-chart)的以下代码,必须分别分配每个数据点,这也占用了大量空间。假设我在列表中同时包含了所有x,y和r。这是一个开放式问题,而不是寻找受限制的解决方案。我将如何实现下面的伪代码?

labelList=['China','Denmark','Germany','Japan']
xlist= [21269017,258702, 3979083,4931877]
ylist = [5.245,7.526,6.994,5.921]
rlist = [15,10,15,15]

datasets: [
    {
      label: labelList,
      data: [{
        x: xlist,
        y: ylist,
        r: rlist
      }]
    }

代替:

new Chart(document.getElementById("bubble-chart"), {
type: 'bubble',
data: {
  datasets: [
    {
      label: ["China"],
      data: [{
        x: 21269017,
        y: 5.245,
        r: 15
      }]
    }, {
      label: ["Denmark"],
      data: [{
        x: 258702,
        y: 7.526,
        r: 10
      }]
    }, {
      label: ["Germany"],
      data: [{
        x: 3979083,
        y: 6.994,
        r: 15
      }]
    }, {
      label: ["Japan"],
      data: [{
        x: 4931877,
        y: 5.921,
        r: 15
      }]
    }
  ]
},
options: {
  title: {
    display: true,
    text: 'Predicted world population (millions) in 2050'
  }, scales: {
    yAxes: [{ 
      scaleLabel: {
        display: true,
        labelString: "Happiness"
      }
    }],
    xAxes: [{ 
      scaleLabel: {
        display: true,
        labelString: "GDP (PPP)"
      }
    }]
  }
}
});

1 个答案:

答案 0 :(得分:1)

首先,您需要检查xListyListrListlabelList的长度是否相同,否则显然我们不能这样做。

之后,我们可以使用如下简单代码生成必要的数据结构:

labelList = ['China', 'Denmark', 'Germany', 'Japan']
xList = [21269017, 258702, 3979083, 4931877]
yList = [5.245, 7.526, 6.994, 5.921]
rList = [15, 10, 15, 15]

if ([labelList.length, xList.length, yList.length, rList.length].every((v, i, arr) => v == arr[0])) {
  datasets = [...Array(labelList.length).keys()].map(i => ({
    label: labelList[i],
    data: [{
      x: xList[i],
      y: yList[i],
      r: rList[i]
    }]
  }))

  console.log(datasets);
}