【问题标题】:ChartJS combine two arrays with some similarities in one plotChartJS 将两个具有一些相似性的数组组合在一个图中
【发布时间】:2021-05-06 07:30:56
【问题描述】:

我需要将两个数组组合成一个条形图,而无需手动操作数组。 数组示例:

result1 = {a:2,b:5,c:52}
result2 = {a:4,b:3,d:47}
//WHERE (to elaborate):
result1.labels = {a, b, c};
result1.data = {2, 5, 52};
result2.labels = {a, b, d};
result2.data = {4, 3, 47};


      var myChart = new Chart(ctx, {
    type: 'bar',
      data: {
          datasets: [{
              label: 'Dataset 1',
              data: result1.data,
              order: 1,
              labels: result1.labels
          }, {
              label: 'Dataset 2',
              data: result2.data,
              order: 2,
              labels: result2.labels
          }]
      },
      options: {
          scales: {
              y: {
                  beginAtZero: true
              }
          }
      }
  });

现在我只会得到 3 条条堆栈,它将合并 result1 和 result2 的 3. 条目,但我需要它来制作 4 条条“a、b、c、d”。 我知道我可以手动填写 result1 并添加“d:0”,然后在 result2 添加“c:0”,但是由于它从不断更改返回数组大小的数据库中获取数据,这不是一个好的解决方案。

谢谢

【问题讨论】:

  • 什么是result1.dataresult1.labels,因为我没有看到对象上的datalabels 属性
  • 你能发布你预期的 result1 和 result2 的输出吗?
  • labels: "a, b, c, d" data: results1 和 2 数组中的数字我只是想简化一下
  • 查看更新的代码片段

标签: javascript charts jscharts


【解决方案1】:

您可以创建一个包含所有键的set,然后遍历该对象并检查该键是否已存在。如果不添加。

const result1 = {a:2,b:5,c:52};
const result2 = {a:4,b:3,d:47};

const getUniqueKeys = (...objs) => {
  // Create a set of all unique keys
  const keys = objs.reduce((keys, obj) => {
    for(key in obj) {
      keys.add(key)
    }
    
    return keys;
  }, new Set());
  
  // Convert set to array
  return [...keys];
}

const addMissingValues = (keys, obj, fill = 0) => {
  // Create copy to prevent changing the original object
  const copy = {...obj};
  
  for(const key of keys) {
    // Add key if it doesn't exist
    if(!copy.hasOwnProperty(key)) {
      copy[key] = fill;
    }
  }
  
  // Return copy
  return copy;
}

const keys = getUniqueKeys(result1, result2);
const correct1 = addMissingValues(keys, result1);
const correct2 = addMissingValues(keys, result2);

console.log(correct1);
console.log(correct2);

【讨论】:

  • 好吧,这也是我的应急方法,只是看起来过于复杂,例如这个条形图可以在 excel 中制作...所以我希望 jschart 有更好的方法
猜你喜欢
  • 2019-10-27
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-13
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
相关资源
最近更新 更多