[Chartjs]-Parse JSON object to ChartJS using object.keys/object.values

1๐Ÿ‘

โœ…

Iโ€™m not 100% sure, what for an output you want/expect, but I would have to say, if you want to display the quarters, you would have to get the values from here data1["AAPL"][0];, in this specific case.

Here a short demo showcasing it:

let data1= { "AAPL": [{
    "Q1": -26986,
    "Q2": -168099,
    "Q3": -137101,
    "Q4": -561990 
}]};

// extracting only the needed data
let initialData = data1["AAPL"][0];

const data = {
  labels: Object.keys(initialData),
  datasets: [{
      label: 'Dataset 0',
      data: Object.values(initialData),
      backgroundColor: '#B0D3FF',
      barThickness: 20,
    }]
};

const config = {
  type: 'bar',
  data: data,
  options: {
    plugins: {
      title: {
        display: false,
      },
      legend: {
        display: false
      }
    },
    responsive: true,
    maintainAspectRatio: false,
    interaction: {
      intersect: false,
    }
  }
};

new Chart(
    document.getElementById('chart'),
    config
);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:184px">
<canvas  id="chart" ></canvas>
</div>

If this is not the desired output, please update your question, with more specifics

Leave a comment