Utilize Object.keys and Object.values to transform a JSON object into a ChartJS representation

I have a unique JSON file structure that I am trying to display in ChartJS. The data looks like this:

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

In my code, I am using the keys as labels and the values as data:

const xmlhttp4 = new XMLHttpRequest();
const url4 = 'https://api.npoint.io/ee3b3d406810c46c44e0';

xmlhttp4.open('GET', url4, true);
xmlhttp4.send();

xmlhttp4.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        const datapoints = JSON.parse(this.responseText);
        const data1 = datapoints[0];
        const barchart = document.getElementById('insider_positions_barchart').getContext('2d');
        
        const myBarChartAUD = new Chart(barchart, {
            type: 'bar',
            data: {
                labels: Object.keys(data1),
                datasets: [{
                    label: 'Net Activity',
                    data: Object.values(data1),
                    backgroundColor: ['rgba(0, 255, 255, 0.2)'],
                    borderColor: ['rgba(0, 255, 255, 1)'],
                    borderWidth: 3
                }]
            },
            options: {
                plugins: {
                    legend: {
                        display: false
                    }
                },
                maintainAspectRatio: false,
                scales: {
                    y: {
                        ticks: {
                            color: "white"
                        },
                        grid: {
                            display: false
                        }
                    },
                    x: {
                        ticks: {
                            color: "white"
                        },
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }
}

I'm facing some issues with getting the data to display correctly in the chart, possibly due to how I am handling the keys and values. Should I consider changing the JSON structure or is there something else I should be looking at?

Answer №1

I'm not completely certain about the type of output you are looking for, but I believe that to display the quarters, you should retrieve the values from data1["AAPL"][0];, in this particular scenario.

Here's a brief demonstration illustrating this:

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 outcome, please provide more specific details in your question.

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

Ruby on Rails: clearing the asset pipeline cache by hand

While Rails usually clears the asset pipeline cache automatically when files are modified, I am facing a unique situation. I am providing my application as an HTML response to an Ajax request, cross-domain using rack-cors to bypass CORS. The issue arises ...

Tips for arranging information in ng-repeat using nested objects within JSON data on AngularJS

Looking to display an array of object properties in an Angular view. Here is the object: $scope._Json = { "foo": { "ItemDimension1": { "Item": "item1", "ItemIndex": 1, "SelectedItems": [{ "C ...

Transmitting a Wav file from JavaScript to Flask

I'm currently working on a JavaScript code that records audio from the browser and now I need to figure out how to send it back to Flask. start: function () { var options = {audio: true, video: false}; navigator.mediaDevices.getUserMedia(optio ...

Is the Positioning of JS Scripts in Pug and Jade Documents Important?

Have you ever wondered why a page loads faster when certain lines are placed at the end of the tag instead of inside it? script(src="/Scripts/jquery.timeago.js") This phenomenon is often seen in code like this: //Jade file with JQuery !!! 5 html(lang=" ...

Component html element in Angular not being updated by service

Within my Angular service, I have a property linked to a text field in a component's HTML. Oddly, when this property is updated by the service, the new value doesn't reflect in the HTML element unless the element is clicked on. I'm perplex ...

Maintaining the selected radio button based on previous input with the use of jQuery or PHP

I am in the process of developing an online quiz system. I am fetching questions and options from getquestion.php through ajax on quiz.html. On this page, I've included next and previous buttons so that users can navigate through the quiz. However, I& ...

Errors in TypeScript are being brought up by using if-else statements inside a loop

I am currently working on a function to retrieve referral codes from users. The user inputs a code, which is then checked against the database to see if it exists or not If the code provided matches the current user's code, it should not be accept ...

Storing Iframe content without the need for a "save button" in a colorbox

I'm currently working on a small project that involves a main HTML page and a separate settings.html file. I've set it up so that the settings page pops up when clicked, using the following code: jQuery('#settings').colorbox({iframe:tr ...

AngularJS combined with the power of WebSockets

I am currently working on a project that involves multiple controllers. One of these controllers requires me to establish a web socket connection, while another needs to listen for messages and update the $scope if necessary. Can you please help me by prov ...

Using a series of functions that make use of (theID)

Hey there, I'm new to HTML and I've been trying to achieve something below. Unfortunately, it's crashing and I can't figure out if it's just a syntax error or if what I'm attempting isn't possible. The function declarati ...

Stopping Form Submission with MUI TextField

I am currently creating a form using React along with MUI. I'm trying to figure out how to prevent the form from being submitted when the user hits the enter key. Usually, I would use e.preventDefault(), but for some reason it's not working in th ...

Determine the date 7 days before today using JavaScript

I've been trying to calculate the date that is 12 days before today's date, but I'm running into an issue where it's not returning the correct result. For instance, if today is November 11, 2013 (mm/dd/yyyy), the code returns October 30 ...

Calculating the mean value from a JSON array

I'm having trouble calculating the average from my variable output. I keep getting NaN or zero as a result. Here is my initial output: console.log(data) 0: {nodeId: "53", SNR: "[38.2, 38, 37.9, 37.8, 37.6]", timestamp: "2019-09-05 00:00:17"} Next, ...

How can I search for a particular string in JavaScript?

I have a unique custom div that has been modified to function as an input element. Inside this custom div input element, there is a <p> tag with a default placeholder text. My goal is to verify whether the content of this div is empty or contains new ...

Integrate Chrome extension using code

Is there a way to programmatically load a Chrome extension? Can it be done using web driver with external extension preferences, or perhaps through JavaScript or another scripting language? ...

What is the process for converting the output of cryptoJS.sha256 to binary in a Postman pre-request script?

Seeking assistance in creating an HMAC signature using a pre-request script in Postman. While troubleshooting, it has become apparent that there is an issue with the signature generation process. Although a proof of concept example provides expected result ...

Navigating advanced search through nuanced filters dynamically with AngularJS

Here you will find the advanced search form: https://i.stack.imgur.com/g7Hiz.png I have successfully created a URL and parameters for document sections, but I am struggling to come up with a solution for managing the "Add Property Restrictions" section w ...

Silencing feature on the video control bar

I recently created a video embedded in a slider, with the intention of removing the start and stop buttons for a seamless experience. However, I now seek to include a mute button so that users have the option to silence videos with sound. Can anyone provid ...

Set default selected value for dropdown list using radio buttons

Could anyone provide guidance on how to reset a dropdown list value using a radio button selection? Specifically, I need the dropdown list to reset to its default "selected" option when a particular radio button is clicked. Any recommended approaches usin ...

Issues with integrating DynamoDB and SES in an Express application due to conflicting configurations

My Objective: I am attempting to run SES code in the app.post route. To achieve this, I have created a configuration file for SES separately and imported it into app.js. However, following the same procedure for DynamoDB configuration is causing a conflict ...