如何使用 ChartJS 中嵌套对象的数据解析图表

How to parse a Chart using data from a nested object in ChartJS

我正在尝试从 json 对象中解析饼图,我通过调用 API 获得该对象。我想使用特定的键值对来呈现饼图本身。

然后我想在我的工具提示中使用一些其他键值结果。

想象一下目前有效的以下场景。

const labels = [
'Januar',
'Februar'
];

const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: ["#0074D9", "#FF4136"],
data: [req('url').current_price.eur, req('url').current_price.eur],
}]
const config = {
  type: 'pie',
  data: data,
  options: {
    responsive: true,
plugins: {
  tooltip: {
    enabled: true,
    usePointStyle: true,
    callbacks: { 
      title: function(tooltipItem, data) {
        console.log(tooltipItem);
        return "Index " + tooltipItem[0].label;
              },

      label: (context) => { 
              console.log('context', context);
                return 'test'
              
      }
    },
  },
},
},
};

const myChart = new Chart(
document.getElementById('myChart'),
config
);

<html>
  <meta charset="UTF-8">

      <div>
        <canvas id="myChart"></canvas>
      </div>
       
</html>

所以我正在尝试的是在没有键的情况下调用 data 中的 API,这样我就可以访问 context 中的对象并使用其中的一些值例如我的标签。

我找到了

parsing: {
                yAxisKey: 'current_price.eur'
            }

config 但如果我根据我的想法更改所有内容,这对我不起作用,因此它呈现 current_price.eur

对于 pie/doughnut 图表,您需要指定 key 选项,因为它不使用任何轴。所以如果你让你的对象像(连同最新版本,3.6.0)这样它应该可以工作:

parsing: {
  key: 'current_price.eur'
}

对象饼图示例:

var options = {
  type: 'doughnut',
  data: {
    datasets: [{
        label: '# of Votes',
        data: [{
          id: 'parent1',
          key: 55
        }, {
          id: 'parent2',
          key: 55
        }, {
          id: 'paren3',
          key: 30
        }],
      },
      {
        label: '# of Points',
        data: [{
          id: 'child1',
          key: 55
        }, {
          id: 'child2',
          key: 55
        }, {
          id: 'child3',
          key: 30
        }, {
          id: 'child4',
          key: 55
        }, {
          id: 'child5',
          key: 55
        }, {
          id: 'child6',
          key: 30
        }],
      }
    ]
  },
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          label: (ttItem) => (`${ttItem.raw.id}: ${ttItem.raw.key}`)
        }
      }
    },
    parsing: {
      key: 'key'
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>