1

How to hide values that are false ? ( 0, null or undefined)

I have tried to do something like

new Chart(this.barCanvas.nativeElement, {

    ...

     data: {
            datasets: [{
                     data: [
                             value < 1 ? null : value,
                             value2 < 1 ? null : value2,
                             valueX < 1 ? null : valueX,
                     ],
            }],
    },
    options: {
            skipNull: true,
    }

    ...

}

chartjs bar

But it doesn't work.

I've found some similar post on SOF with no answers or working solution

Inspired on LeeLenalee answer and zhulien comment I have created a variable chartData that I filter before passing it.

But passing the variable chartData make a type error on data (to copy past the object of chartData and passing it directly does not make a type error, but the view of the graph does not load)

indexToRemove is an array of index based on data that are to 0

var chartData = {
      labels: ['Batterie faible', 'Maintenance', 'HS', 'Place libre', 'Place occupée'].filter((v, i) => indexToRemove.includes(i)),
      datasets: [{
        label: '',
        data: data.filter((v, i) => indexToRemove.includes(i)),
        backgroundColor: [
          '#F6741A',
          '#dc2625',
          '#B91C1B',
          '#22c55e',
          '#FACC14'
        ].filter((v, i) => indexToRemove.includes(i)),
        borderRadius: 4,
        borderSkipped: false,
      }]
    }

    new Chart(this.barCanvas.nativeElement, {
      type: 'bar',
      data: chartData, // <- Type error (But replacing by the object correct the type error but still does not work as said above)
    ...
    }
4

1 回答 1

2

您可以先过滤您的数据,并与它一起使用对象表示法:

let initialData = [{
    "x": "label1",
    "y": 9
  },
  {
    "x": "label2",
    "y": 0
  },
  {
    "x": "label3",
    "y": 5
  },
  {
    "x": "label4",
    "y": 10
  },
  {
    "x": "label6",
    "y": null
  },
  {
    "x": "label7",
    "y": 3
  },
  {
    "x": "label8",
    "y": undefined
  }
];
let data = initialData.filter(e => e.y);

const options = {
  type: 'bar',
  data: {
    datasets: [{
      label: '# of Votes',
      data: data,
      backgroundColor: 'pink',
    }]
  },
  options: {}
}

const 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.7.0/chart.js"></script>
</body>

于 2022-01-03T16:23:24.207 回答