Charting multiple datasets in a line graph based on provided tabular

I am currently working on generating a multi-set line graph using Chart.js and Angular. With the help of map function, I have been able to transform the JSON data into a single-dimensional array. However, my challenge lies in converting one of the columns (head) as the label, average column as the y-axis, and timestamp column as the x-axis.

Here is a sample JSON format output from the database:

const dataset = 
[{id:1, head:test1,timestamp:5/6/2019,average:12},
{id:2, head:test1,timestamp:6/6/2019,average:15},
{id:3, head:test2,timestamp:5/6/2019,average:7},
{id:4, head:test2,timestamp:6/6/2019,average:20},
{id:5, head:test3,timestamp:6/6/2019,average:13}]

The expected format for Chart.js for the multi-y-axis output should look like this:

{data : [12, 15], label:test1},
{data : [7, 20], label:test2},
{data : [0, 13], label:test3},

Although I can easily convert each column's data into a single-dimensional array, there could be discrepancies if I attempt to create a graph directly from it since the whole dataset has been converted to a 1D array.

const labels = dataset.map(function(obj) {return obj.head});
const tstamp = dataset.map(function(obj) {return obj.timestamp});
const tavg = dataset.map(function(obj) {return obj.average});

I would appreciate any suggestions you may have on how to properly convert the data into the expected format.

Answer №1

To start, begin by reducing the object through indexing:

const information = dataset.reduce((accumulator, item) => {
  if (accumulator[item.header] == null) accumulator[item.header] = { details: [], tag: item.header };
  accumulator[item.header].details.push(item.average);
  return accumulator;
}, {});

Next, retrieve values from the result

const outcome = Object.values(information);

Then, add padding to the .details field in order to achieve the correct structure

outcome.forEach(line => {
  while (line.details.length < 2) 
    line.details.unshift(0);
});

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

Issue with fading out in Ajax.BeginForm not resolving

I currently have: @using (Ajax.BeginForm("actionToDo", new AjaxOptions { HttpMethod = "post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "updatediv", OnBegin = "$('#updatediv').fadeOut()", OnComplete = "$(&apo ...

What is the best way to access all sections of a JSON file containing nested objects within objects?

Here is an example of my JSON file structure: [{ "articles": [ { "1": { "sections": [ {"1": "Lots of stuff here."} ] } }, { "2": { "sections": [ {"1": "And some more text right here"} ] } } }] The c ...

"Enhance Your Browse experience: Chrome Extension that automatically appends content to pages

I'm currently developing a Chrome extension that detects when a URL on a specific domain changes, and if the URL matches a certain pattern, it will add new HTML content to the webpage. Here is an excerpt from my manifest.json file: { "name": "Ap ...

The ajax Success function fails to work when set to receive JSON data

My task involves adding an attendance record for a group of students within a classroom using a Bootstrap modal. Below is the code snippet for my Bootstrap modal, containing a form: <div id = "add_attendance_modal" class = "modal fade&qu ...

Failure to receive Ajax XML data in success callback

I am struggling to access the book.xml file that is located in the same folder as other files. Everything seems fine, but the ajax function refuses to enter the success state and instead shows an [object object] error message. The XML file is very simple, ...

Updating the id token in VueJs using Axios interceptor when it expires

I need to implement an axios interceptor that will add the idToken as an authorization header to every axios call, and also refresh the idToken if it has expired before making any call. My current code for this task is as follows: axios.interceptors.requ ...

Evaluating the Material ui Select element without relying on test identifiers

Currently, I am working with Material UI and react-testing-library to test a form. The form includes a Select component that is populated by an array of objects. import React, { useState } from 'react'; import { Select, MenuItem, FormControl, Inp ...

Steps to disable all fields if the previous field is set to its default value and the default value is currently selected

As a newcomer to AngularJS, I have successfully disabled fields based on previous field selections. However, my goal is to set the default value of "ALL" for all fields (country, state, city). If the country value is set to "ALL," then the state and city ...

"Exploring the power of Knockout JS by utilizing the foreach loop to iterate through

I have an observableArray: self.stats = ko.observableArray([ {"DFTD" : new Stat("Defensive TD", "DFTD",0,20,0,self.playerGroups[1])}, {"GL" : new Stat("Games Lost", "GL",0,16,0,self.playerGroups[2])}, {"FGA" : new Stat("Field Go ...

The conditional statements within the resize function may not always be triggered when the conditions are fulfilled

Struggling to trigger a function only once when resizing. The issue is that the conditional statements are not consistently executed every time. Here's the code snippet: var old_width = $(window).width(); $(window).on('resize.3col',functio ...

Locating discord.js users who possess multiple roles

Here is my code in its entirety as I have received some confusion on other forums: I am working on creating a Discord bot that can list users with a specific role. The plan is to create an array of roles, compare user inputs to the array, and display user ...

Clicking does not trigger scrollIntoView to work properly

I'm facing an issue with a button that is supposed to scroll the page down to a specific div when clicked. I implemented a scrollIntoView function in JavaScript and attached it to the button using onClick. Although the onClick event is functioning as ...

Tips for sending parameters using arrow functions within ReactJS hooks

I've recently started working with ReactJS and I'm a bit confused about how to pass parameters using arrow functions. I attempted to use .bind() in order to bind the value so it can be used in the function, but unfortunately that didn't work ...

Disordered dropdown display

I've implemented a class that conceals the 2nd and 3rd dropdown options until there's a click or change in the 1st selection. Current Behavior After choosing "regular" from the dropdown, the execution of $(".dropdown").removeClass(&quo ...

The vue-pdf is having trouble loading all pages due to an "undefined property" issue

I am currently utilizing the following technologies: Vue.js, vue-route, Vuetify, Firebase (with a database) and vue-pdf The issue I am facing involves attempting to load all pdf pages using "vue-pdf" plugin. However, when trying to read the pdf, I encoun ...

I am looking to dynamically assign an href attribute to a link using a variable within my script. How can I achieve

I am working on displaying an image inside a jQuery slider with the following HTML markup:- <li> <figure> <a href="~/img/big.jpg" class="thumb"> <img src="~/img/small.jpg" alt=""/> <span> ...

Creating a JavaScript function that calculates the sum of values in a table

Here is a snippet of my HTML code: <TR Row="1" CLASS="ThemeAlignCenter"> <TD id="wrdActive_Row1" style="width: 50px" CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">6</SPAN></TD> .. ...

Exporting an indexed geometry with a draw range using GLTFExporter in Three.js: What's the best approach?

I am encountering a specific issue where I need to export an indexed geometry with a draw range. Unfortunately, the GLTFExporter does not support this feature, as indicated by the comment in the code: // @TODO Indexed buffer geometry with drawRange not su ...

How can I convert the left links in my navigation bar to a CSS drop-down menu to make it more responsive on small screens?

Here is the structure of my HTML (at the top): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></s ...

Getting a vnode from a DOM element in Vue 3.0: A Step-by-Step Guide

My question pertains to obtaining a vnode through accessing the DOM using document.getElementById(id). How can I accomplish this? ...