Convert JSON information for use in ChartJS

I've been delving into the world of ChartJs and have encountered a bit of a roadblock. I'm looking to decipher how to convert JSON data into labels and data for a bar chart.

The JSON data consists of an array of product orders. With varying numbers of products, I need to sift through and compile a list of products for the ChartJS labels. Following that, I need to tally how many times each product appears in the JSON in order to determine the number of times each product was sold.

[

{
    "order_id": 1,
    "product_name": "apple"
  },
  {
    "order_id": 2,
    "product_name": "orange"
  },
  {
    "order_id": 3,
    "product_name": "orange"
  },
  {
    "order_id": 4,
    "product_name": "monster truck"
  },
  {
    "order_id": 5,
    "product_name": "spark plug"
  },
  {
    "order_id": 6,
    "product_name": "apple"
  },
  {
    "order_id": 7,
    "product_name": "can of peaches"
  },
  {
    "order_id": 8,
    "product_name": "monster truck"
  },
  {
    "order_id": 9,
    "product_name": "orange"
  },
  {
    "order_id": 10,
    "product_name": "orange"
  }

  ]

I aim to generate two arrays for the product labels and order counts

Labels: ["apple", "orange", "monster truck", "spark plug", "can of peaches"]
Orders: [2, 4, 2, 1, 1]

Any guidance on the best way to accomplish this task?

Answer №1

Here's a slightly shorter solution that you can also try:

//@ts-nocheck

const products = [
  {
    order_id: 1,
    product_name: "apple",
  },
  {
    order_id: 2,
    product_name: "orange",
  },
  {
    order_id: 3,
    product_name: "orange",
  },
  {
    order_id: 4,
    product_name: "monster truck",
  },
  {
    order_id: 5,
    product_name: "spark plug",
  },
  {
    order_id: 6,
    product_name: "apple",
  },
  {
    order_id: 7,
    product_name: "can of peaches",
  },
  {
    order_id: 8,
    product_name: "monster truck",
  },
  {
    order_id: 9,
    product_name: "orange",
  },
  {
    order_id: 10,
    product_name: "orange",
  },
];

const map = {};
products.forEach(
  (product) =>
    (map[product.product_name] = (map[product.product_name] ?? 0) + 1)
);

const Labels = Object.keys(map);
const Orders = Object.values(map);
console.log({ Labels, Orders });

Answer №2

let items = [

    {
        "item_id": 1,
        "item_name": "banana"
    },
    {
        "item_id": 2,
        "item_name": "grapes"
    },
    {
        "item_id": 3,
        "item_name": "grapes"
    },
    {
        "item_id": 4,
        "item_name": "bicycle"
    },
    {
        "item_id": 5,
        "item_name": "flashlight"
    },
    {
        "item_id": 6,
        "item_name": "banana"
    },
    {
        "item_id": 7,
        "item_name": "watermelon"
    },
    {
        "item_id": 8,
        "item_name": "bicycle"
    },
    {
        "item_id": 9,
        "item_name": "grapes"
    },
    {
        "item_id": 10,
        "item_name": "grapes"
    }

];

const categories = [...new Set(items.map(value => value.item_name))];
const quantities = categories.map(value => {
    return items.reduce((previousValue, currentValue) =>  {
        console.log(currentValue);
        if (currentValue.item_name === value) {
            return previousValue + 1;
        }
        else {
            return  previousValue;
        }
    }, 0);
});

Learn more about these array methods here:

The Set is utilized to extract only the unique values in an array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/Set

Since the Set object lacks certain methods, we convert it back to an Array using the spread operator (...)

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

Laravel: Input information into a form containing multiple dropdown menus

I am in search of a Laravel or HTML example that demonstrates filling out a form with multiple drop-down lists. Here's my scenario: I have the following text inputs: name_customer, phone_customer, email_customer. I want the form fields to automatical ...

Using AngularJS ng-repeat to pass href links

I am facing an issue with displaying hyperlinks in a list of messages obtained from server response using AngularJS. $scope.messages = [] When a button is clicked, the content of a text area is added to the array using ng-click method. This message is th ...

Press the key to navigate to a different page

I have an input field for a search box. I want it so that when I enter my search query and press enter, the page navigates to another page with the value of the input included in the URL as a query string. How can I achieve this functionality? Thank you ...

Verify the type of email domain (personal or corporate)

Here's an example: isPersonalEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aea1ada580a7ada1a9aceea3afad">[email protected]</a>") // true isPersonalEmail("<a href="/cdn-cgi/l/email- ...

Is there a way to convert time measurements like minutes, hours, or days into seconds in React and then pass that information to an

Currently, I am working on an application that allows users to select a frequency unit (like seconds, minutes, hours, or days) and input the corresponding value. The challenge arises when I need to convert this value into seconds before sending it to the ...

The use of Handlebars expressions within the {{#each}} block is crucial

I am currently working on my new portfolio site and I have a question about how to place handlebars expressions inside an #each loop. The project is an express application generated by express-generator, and I am using the express-handlebars NPM package: ...

What could be causing me to receive no results?

Currently, I am expanding my knowledge in JavaScript, Ajax, and NodeJs. My current project involves creating a webpage that can display a string retrieved from the server. The server-side code is as follows: var express = require('express'); v ...

initiate a page refresh upon selecting a particular checkbox

So I've got this code that saves around 30 checkbox selections to local storage, which is working fine. Then there's this separate checkbox below, when checked it automatically reloads the page: <input type="checkbox" id="autoload" class="aut ...

Oops! The regular expression flag "ajax" in Javascript is not valid and is causing

This is my function: public ActionResult RetrieveData(int id) { string name = "Jane"; return Json( new {result=name}); } I'm attempting to fetch information from this function using the code below, but I keep getting errors. Could y ...

Adding Axios package to a Vue 3 project without using the CLI

I'm facing an issue while trying to integrate the Axios package into my Vue 3 project that is not CLI-based. I initially attempted to include the package within the script tags at the top of the page, but that approach failed. Next, I tried creating a ...

Altering the DOM directly within the componentDidMount() lifecycle method without needing to use

In ReactJS, I am facing an issue while trying to manipulate the DOM in the componentDidMount() method. The problem lies in the fact that the DOM is not fully rendered at this point, requiring me to use a setTimeout function, which I find undesirable. Upon ...

Add or remove an ID from the swatch gallery based on its presence or absence

I'm currently working on a handleClick function for a gradient swatch gallery. The goal is to add an id of "bg-gradient" to the clicked element, and if another swatch is clicked, remove that id from the previously clicked swatch and add it to the newl ...

The functionality of jQuery on dropdown list change seems to be malfunctioning in Codeigniter

As a novice in CodeIgniter, I've scoured various StackOverflow threads for a solution to my issue without any luck. Below is the view code causing trouble: <select name="select1" id="select1"> <option value="0">None</option> ...

Having trouble getting Fullcalendar to show up on my cordova app

Currently, I am in the process of building a mobile application using ionic and cordova. My goal is to incorporate a timetable system utilizing Fullcalendar and a PHP page that showcases MySQL data in JSON format. Despite my efforts, I am encountering diff ...

Deploying an Angular application created using Yeoman to Heroku

I have been following some instructions on how to deploy my project, such as this guide or this tutorial. However, I am unable to get it to work properly. This is the code in my server.js file: var app, express, gzippo, morgan; gzippo = require('gz ...

Modify the color of the components in Select from Material-UI

After reviewing numerous questions and answers on this topic, I have yet to find a suitable solution for my issue. Seeking guidance from the community for assistance. Utilizing the Select component from @mui/material to showcase the number of records per ...

Load a form using ajax and submit it using jQuery

For a while now, I have been facing challenges in figuring out what's going wrong with my code. The issue arises when I try to submit a form using jQuery that was loaded through ajax. The form loads perfectly fine within a div after invoking the ajax ...

Rotation Causes Vertices to Deviate from Expected Axis Movement

While moving the vertices of a shape on mouse move works well, applying a rotation to the shape causes the vertices to move along the wrong axis. If you'd like to see the issue in action, check out this codesandbox.io link: https://codesandbox.io/emb ...

The Next.js application encounters a crash when trying to integrate Google Firebase authentication

I'm encountering an issue while trying to integrate authentication using firebase (via Google) in my next.js application, and the app crashes consistently. I will provide the code for the auth.js page component, as well as where I set up firebase and ...

The PHP AJAX call is returning an undefined response status

I'm facing two issues here. The first problem is that when I try to access response.status, it returns undefined. The second issue is related to the creation of "$_SESSION['promo-code'] = $arr". When I enter a promo code, I encounter the fol ...