Retrieve information from json, divide it, and transfer it to the chart for display

Greetings everyone! In my project, I am parsing a JSON file from an online API. However, I have encountered a roadblock while trying to split the data. Despite searching extensively on platforms like YouTube, I haven't been able to find a solution that fits my needs. As a newcomer to JavaScript, I am struggling with this task. The structure of the JSON file looks like this:

"timeline": {
"cases": {
"8/29/21": 1874435,
"8/30/21": 1881213,
"8/31/21": 1888150,
"9/1/21": 1895459,
"9/2/21": 1902407,

My goal is to visualize this data in a chart.

For creating charts, I am using ApexCharts. Here is a snippet of my code:

 
    dayno = 30; 
url = "https://disease.sh/v3/covid-19/historical/iraq?lastdays=" + dayno; 
var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};
// .then(result => console.log(result.timeline.cases)
const {cases}= timeline;
fetch(url, requestOptions)
  .then(response => response.json())
  .then(result => console.log(result.timeline.cases))
 
  .then(result => console.log(result))
  .catch(error => console.log('error', error));


  var options = {
    chart: {
      height: 280,
      type: "area"
    },
    dataLabels: {
      enabled: false
    },
    series: [
      {
        name: "Series 1",
        data: [45, 52, 38, 45, 19, 23, 2] // number of cases after split it
      }
    ],
    fill: {
      type: "gradient",
      gradient: {
        shadeIntensity: 1,
        opacityFrom: 0.7,
        opacityTo: 0.9,
        stops: [0, 90, 100]
      }
    },
    xaxis: {
      categories: [
        "01 Jan", // date here from split 
        "02 Jan",
        "03 Jan",
        "04 Jan",
        "05 Jan",
        "06 Jan",
        "07 Jan"
      ]
    }
  };
  
  var chart = new ApexCharts(document.querySelector("#chart"), options);
  
  chart.render();

Answer №1

Avoid using categories in the xaxis for simple date charts.

Instead, it is recommended to specify type: "datetime".

xaxis : { type: 'datetime' }

When fetching data, make sure to format it accordingly.

fetch(url, requestOptions)
  .then(response => response.json())
  .then(result => {
  let tempSerie = {name: 'cases', data: []}
  for (const [key, value] of Object.entries(result.cases)) {
  tempSerie.data.push([key, value]);
  }
  chart.updateSeries([tempSerie]);
  })
  .catch(error => console.log('error', error));

Create a temporary series variable to store an object with the name cases and an empty data array.

Iterate through the object properties and push a new [key, value] array to the data array.

Finally, update the chart series accordingly.

Answer №2

I have made some changes to your code below. Kindly review and see if it resolves the issue. You can utilize javascript Object.keys to fetch the keys of objects and Object.values to retrieve the values of the JSON object.

dayno = 30; 
url = "https://disease.sh/v3/covid-19/historical/iraq?lastdays=" + dayno; 
var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};
// .then(result => console.log(result.timeline.cases)
const {cases}= timeline;

fetch(url, requestOptions)
  .then(response => response.json())
  .then(result => console.log(result.timeline.cases))
 
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

const series1 = Object.values(cases);
const dates = Object.keys(cases);

  var options = {
    chart: {
      height: 280,
      type: "area"
    },
    dataLabels: {
      enabled: false
    },
    series: [
      {
        name: "Series 1",
        data: series1 // number of cases after split it
      }
    ],
    fill: {
      type: "gradient",
      gradient: {
        shadeIntensity: 1,
        opacityFrom: 0.7,
        opacityTo: 0.9,
        stops: [0, 90, 100]
      }
    },
    xaxis: {  
      categories: dates // date her form split
    }
  };
  
  var chart = new ApexCharts(document.querySelector("#chart"), options);
  
  chart.render();

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

"Vue Filepond: Enhancing Your Images with Cropping

Currently, I am integrating filepond with VueJS to facilitate image uploads. To enable image cropping during upload, a specific configuration is required. The filepond plugin has been globally registered, as shown below: import Vue from 'vue'; i ...

Canvas displaying inaccurately (unsteady)

While working on a simple HTML5/javascript game, I encountered an unusual issue with the canvas drawings - they seem to be unstable. I have a map that needs to be drawn in a specific way: The background consists of 2 layers: the ocean and the islands. Th ...

Steps to configure npm start for an electron application using "babel-node --presets es2015,stage-3"

I've been experimenting with getting my npm start to work properly for electron. Typically, you would start a non-distributed app with electron . or ./node_modules/.bin/electron .. However, due to my use of NodeJS v8.4.0 and ES6/7 syntax, my npm start ...

Is JSONP necessary for accessing the API subdomain?

Currently in the process of setting up an application with the API being hosted at http://api.project.com while the main app will reside at https://app.project.com. This app is going to be entirely based on angular.js. I'm curious if JSONP is the onl ...

Sort the currency column in an HTML table through JavaScript

I have a code snippet below that I'm currently utilizing to arrange columns in an HTML table. The code works perfectly for alphabetical sorting and also for single-digit numbers. However, when attempting to sort a column containing currency values, t ...

What is the process of encoding JSON in PHP using jQuery Ajax to send post data?

I created an HTML form to submit data to a PHP file upon hitting the submit button. $.ajax({ url: "text.php", type: "POST", data: { amount: amount, firstName: firstName, lastName: lastName, email: email }, ...

The Material-UI DataGrid feature allows for the display of column sums, with the sum dynamically updating based on applied filters

I am struggling with calculating the sum of values in the Total Amount column of my Material-UI DataGrid. How can I achieve this and ensure that the sum is also updated when a filter is triggered? Any guidance on how to sum the entire Total Amount column ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...

Nuxt.js ERROR: Unable to find reference to 'window' object

Currently working with Nuxt.js and encountering an issue while configuring vuex-persist. Seeking assistance from someone familiar with this problem. store/index.js store/LangModule.js ...

In the callback function within Array.prototype.map, make sure to access the newly created array

Array.prototype.map() creates a new array. How can I use this new array within the callback function passed to Array.prototype.map()? For instance: someArray.map(function(item, idx, arr) { return { theCreatedArray: xyz }; }); What should I assign to ...

Retrieving a value in the app component from a map using Angular

I have been struggling to display the values of ValueM, ValueR, and product in my app.component.html file. Can anyone offer a solution or tip to help me move forward? Thank you very much. app.component.ts forkJoin( this.service1.method1(filter1), ...

Color schemes for items in the Windows store app

I'm having trouble changing the background color of an item in my split application. I've tried using CSS, but nothing seems to work. Here is the template for the item (default style): <div class="itemtemplate" data-win-control="WinJS.Bindin ...

Upon the initial hover, the data added to the title tag following an Ajax call is not appearing

I am currently working on an ajax request that retrieves information such as username, email, and user_id. Once the ajax call is successful, I use jQuery to append this data to the title tag. The main issue I am facing is that the data is only displayed af ...

Using the useState hook in a loop can sometimes result in a unique key error

Trying to add multiple items for rendering in my browser, but encountering an issue after clicking addItem. The item does render, however, I am getting the following error message: 'Warning: Each child in a list should have a unique ""key"" ...

Reloading and redirecting web pages with PHP and Ajax techniques

I am currently working on a registration form in PHP. I have implemented validations for the input fields and used AJAX to handle the form submission. Everything seems to be functioning properly, except that when the submit button is clicked, the success ...

The Node Express.js app is functioning properly when run locally, but displays the error "Cannot GET /" when running in a Docker container

My Node application has an Express.js server defined like this: const express = require('express') const SignRequest = require('./SignRequest/lambda/index.js') const VerifyResponse = require('./VerifyResponse/lambda/index.js') ...

What is the best way to generate an empty object that mimics the structure of an object within an array of objects in AngularJS

I am facing a scenario where I have an array of objects structured like this: $scope.users = [ { ID: "1", Name: "Hege", Username: "Pege", Password: "hp", }, { ID: "2", Name: "Peter", User ...

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...

Elements animated using intersection observer are inconsistently functioning on the current page

My current challenge involves animating elements with the intersection observer, but I am encountering strange behavior with elements that are already on the screen when the page loads. These elements sometimes animate correctly and other times they do no ...

Is it feasible to generate a fixed lighting effect overlay with HTML and CSS?

Is it possible to incorporate a static lighting effect overlay using HTML/CSS? My project consists of an HTML5/JS app with a top navigation bar and a series of cards that are transitioned through using swipe gestures. These cards are displayed in gray ove ...