"Explore the possibilities of showcasing your JSON data in a visually striking way with the Chart

Just starting out with chartjs and looking to create some charts using JSON data. I have the following JSON array that I want to display in a chart similar to this Sample Image. Any help would be appreciated!

[
      {
        "ChartGroupName": "Group-A",
        "Apple": 45,
        "Banana": 37,
        "Kiwi_fruit": 60,
        "Blueberry": 70,
        "Orange": 46,
        "Grape_Fruit": 33
      },
      {
        "ChartGroupName": "Group-B",
        "Apple": 50,
        "Banana": 35,
        "Kiwi_fruit": 70,
        "Blueberry": 65,
        "Orange": 40,
        "Grape_Fruit": 53
      },
      {
        "ChartGroupName": "Group-C",
        "Apple": 55,
        "Banana": 39,
        "Kiwi_fruit": 80,
        "Blueberry": 75,
        "Orange": 52,
        "Grape_Fruit": 73
      }
    ]

Answer №1

To generate the labels and datasets from your JSON data contained in an array named data, you can use the following code:

const labels = Object.keys(data[0]).slice(1).map(label => label.replace('_', ' '));
const datasets = data.map((obj, index) => ({
    label: obj[0],
    data: Object.values(obj).slice(1),
    backgroundColor: colors[index]
  })
);

Check out the runnable code snippet below to see this in action.

const data = [
  {
    "ChartGroupName": "Group-A",
    "Apple": 45,
    "Banana": 37,
    "Kiwi_fruit": 60,
    "Blueberry": 70,
    "Orange": 46,
    "Grape_Fruit": 33
  },
  {
    "ChartGroupName": "Group-B",
    "Apple": 50,
    "Banana": 35,
    "Kiwi_fruit": 70,
    "Blueberry": 65,
    "Orange": 40,
    "Grape_Fruit": 53
  },
  {
    "ChartGroupName": "Group-C",
    "Apple": 55,
    "Banana": 39,
    "Kiwi_fruit": 80,
    "Blueberry": 75,
    "Orange": 52,
    "Grape_Fruit": 73
  }
];
const colors = ['orange', 'yellow', 'lightblue']

const labels = Object.keys(data[0]).slice(1).map(l => l.replace('_', ' '));
const datasets = data.map((o, i) => ({
    label: o['ChartGroupName'],
    data: Object.values(o).slice(1),
    backgroundColor: colors[i]
  })
);

new Chart('myChart', {
  type: 'bar',
  data: {
    labels: labels,
    datasets: datasets
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart"></canvas>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Div element triggers a focus event when either the div itself is selected or any nested input field is selected - Angular

Within an Angular application, I have a Div element with an index tab that allows for selection. This Div contains a form with various fields and buttons. My goal is to trigger the focus event on the Div whenever the Div itself is selected or any element w ...

Type 'Partial' cannot be assigned a value when combining interfaces with generic types

Consider the following scenario: class Table<ValuesType extends DefaultTableValues = DefaultTableValues>{ public values: ValuesType; constructor(initialValues:ValuesType) { this.values=initialValues; } public set(newValues:Pa ...

Error: Unable to locate the custom module - TS2307

We have recently taken over a Next + TypeScript website from another developer and are attempting to create a new component that is heavily based on an existing one. I have duplicated the entire component and its subfolders at the same level as the origina ...

Issue with Angular 2's ngModelChange function in the second dropdown causing it to malfunction

I am facing an issue with two dropdown menus that have different ngModelChange methods: <div class="mb-40"> <div class="tit03 mb-20">Type of Healthpros</div> <select class="form-control" [(ngModel)]="pros" (ngModelChange)="onSelec ...

Angular's Out of the Box Themes

Just starting out with Angular. I was wondering if there are any built-in themes in Angular 6 or 7? Interested in incorporating them into my Angular application. ...

Guide to combining ngModel with the index value in Angular Material

My issue involves implementing a dynamic table with Angular Material. In each row of the table, there is a select dropdown field. Initially, the button beside the dropdown is disabled. The desired behavior is for this button to become clickable as soon as ...

How can you dynamically disable the submit button on a form in Angular 7+ based on the form's current status?

Let's consider a scenario with a button in our code: <button type="button" class="menu-button" [disabled]="isInvalidForm()">Save</button isInvalidForm() { console.log('I am running!'); return this.nameValidator.errors || this.last ...

Angular - Utilizing Reactive Forms for Nested Object Binding

I have created a FormGroup and initialized it with one formControlName called SerialNumber. The JSON structure for SerialNumber is as follows: { "SerialNumber": { "snValue": "332432" } } I am struggling to bin ...

Tips for concealing function parameter missing type notifications

For my TypeScript development in VS Code, I have noticed a new behavior since the 1.30 release. There is now a three dots mark next to functions without a defined type, as shown in this screenshot. When I hover over it, a notice pops up saying "Parameter ...

Is it possible for object destructuring in Javascript to include dynamic non-rest keys using ...rest?

Suppose we have an object: const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" }; My goal is to filter out specific keys from this object to create a smaller one. I am aware of the following ...

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

Error: Axios header not refreshing automatically in React. User must manually refresh the page

After logging in, I want to update the JWT token in the header before redirecting to the home page. Login.tsx ... const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const data = new FormData(event.curr ...

Displaying a limited number of dynamically generated values in an Angular select dropdown using Bootstrap 5

I have a backend service that provides a list of all countries. In my component, I iterate through the array and allow the user to select a country. Bootstrap 5 is being used for styling. <select class="form-select" formControlName="coun ...

Typescript: parameter must be included if another is also required

In the user interface, the parameter c is mandatory only if the parameter a is set to true. interface IArguments { a: boolean, b: string, c: string } The solution below seems to be effective, but how can I exclude the c parameter in the first scenar ...

Wrong method executed when trying to use Angular http put

I am facing an issue with my http.put wrapper where it is calling the incorrect PUT overload. I specifically need the one that returns Observable<Object>, but instead it is calling Observable<ArrayBuffer>. Here is the code snippet for my http.p ...

After filtering the array in JavaScript, perform an additional process as a second step

My task involves manipulating an array through two methods in sequence: Filter the array Then, sort it The filter method I am using is as follows: filterArray(list){ return list.filter(item => !this.myCondition(item)); } The sort method I a ...

Is it possible to reset the attributes of a container's children using a renderer?

Within a container, there are dropdowns, multiple selects, and quantity selections. When a button is clicked, I aim to reset the state of the component. https://i.stack.imgur.com/TY5un.png <input #select type="checkbox" value="somevalue"/> The ...

Building a route to a link in Next.js: A step-by-step guide

Having trouble setting up routes to my Next.js portfolio project page. I've created an array of pages and their links in the index.ts file within the data folder, but I'm facing issues with routing. I've integrated a floating navigation usi ...

Accessing HTTP data through a function instead of using ngOnInit in Angular is a more efficient approach

Trying to retrieve data from a service using setInterval has posed an issue for me. When I call the service from ngOnInit, everything functions as expected. However, when attempting to call it from any other function, an error occurs: "ERROR TypeError: Ca ...

Can you verify that the client's date and time locale are accurate in JavaScript before proceeding with processing?

For my application, I am seeking the current locale datetime. However, before retrieving the date, it is crucial to verify that the local date and time are accurate. If the user has adjusted the date and time incorrectly on their machine, I must prompt a ...