Automatically calculate the quantity of pie charts to showcase and present each one individually on a CanvasJS-generated page

I am looking to create multiple pie charts dynamically and display them together on a webpage. The number of pie charts needed will be determined by the elements in a JSON object. Here is an example of how the data will be structured:

[
  {
    "id" : "123",
    "data" : [20, 40, 10, 20, 10]
  },
  {
    "id" : "456",
    "data" : [10, 20, 20, 30, 20]    
  },
  {
    "id" : "789",
    "data" : [25, 35, 5, 10, 25]
  }
]

My goal is to have a pie chart for each element that contains both 'id' and 'data' attributes. The 'data' values will be used as dataPoints in the pie charts for their corresponding 'id'. How can I go about achieving this?

Answer №1

Successfully extracting data from JSON and transferring it to chart options. See the provided code snippet below:

var dataPoints = [];
var dataSeries = [];
var charts = [];

$.when( $.getJSON("https://api.myjson.com/bins/us9mk", function(result) {  
  for(var i = 0; i < result.length; i++) {
    dataPoints = [];
    for(var j = 0; j < result[i].data.length; j++) {
      dataPoints.push({y: result[i].data[j]});
    }
    dataSeries.push({id: result[i].id, type: "pie", dataPoints: dataPoints})
  }
})).then(function( data, textStatus, jqXHR ) {
  for(var i = 0; i < dataSeries.length; i++) {
    $("#chartsContainer").append("<div id='" + dataSeries[i].id + "' style='width: 100%; height: 200px;'></div>");
    charts[i] = new CanvasJS.Chart(dataSeries[i].id, {
      title: {
        text: dataSeries[i].id
      },
      data: [dataSeries[i]]
    });    
    charts[i].render();
  }
});
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="chartsContainer"></div>

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

Extracting POST information through PHP's AJAX Request

I am facing an issue where I keep receiving null values when using the following code: Here is my Ajax request: formData = { u: "3959eeadb32e02b85a792e21c", id: "6d7613df26" }; $.ajax({ ...

Mock needed assistance

In my testing scenario, I am attempting to simulate a service that is utilized by my function using sinon. However, I am encountering difficulties in inserting the mock into my function. The service is obtained through the use of require The structure of ...

Connect an Angular Service object to a Controller's Scope and keeping it in sync

I am facing an issue with the interaction between my EmployeeService and EmployeeController. The service contains a specific object which I bind to the controller's scope: app.controller('EmployeeController', function($scope, EmployeeServic ...

Javascript function to deselect all items

One of my functions is designed to reset all checkbox values and then trigger an AJAX request. However, there are instances when the function initiates before the checkboxes have been unchecked. function clear() { $("#a").prop("checked", false); $("#b ...

Transforming HTML tables into JSON using JQuery

My table contains rows with specific classes, and I need to convert it into JSON for server-side usage. Below is the content of the table: <table class="tableContent"> <thead> <tr class="header"> <th class="col1">RoleNa ...

Utilizing ng-if within ng-repeat for dynamically generated option tags in HTML and AngularJS

I am using AngularJS to create a dropdown menu with select and option tags. The menu is referencing a model and looks like this: <select id="edit-location" class="" ng-model="packageLoc"> <option ng-repeat="x in loc" value="{{ x.locationId }} ...

What is the process of implementing FFT in node.js?

Struggling with implementing FFT in node.js is proving to be quite challenging for me at the moment. Despite experimenting with three different libraries, I find them all poorly documented, which only adds to the complexity of the task. My current setup i ...

Unveil concealed information within a freshly enlarged container

As I organize my content into an FAQ format, I want users to be able to click on a link and expand the section to reveal a list of items that can also be expanded individually. My goal is to have certain list items expand automatically when the FAQ section ...

DRF: Error - Unable to serialize <Model: Model object> as JSON

Encountered a challenge with extracting object data from a request using django-rest-framework ModelViewset create(self, request) method. Below is the code snippet from my model.py class Heat(models.Model): # Relationship Fields animal = models. ...

I would like for this message to appear periodically following the initial execution

I have developed a unique welcome feature using HTML and CSS that I would like to showcase intermittently. --------------------------- My Desired Outcome --------------------------- Initially, this feature should be triggered once (when a user first acce ...

Despite calling this.setState to update my state, the render() method is still displaying the previous values

class EditLocation extends Component { constructor(props) { super(); this.state = { LocationId: '', locationOptions: [], } this.baseState = this.state; this.findLocationById = this ...

Steps to retrieve an ext.js grid using data from a database

I've been struggling to make a basic Ext.js application work, which is supposed to pull data from a database and show it in an Ext.js grid. However, all I keep getting is "Failure:true". If you could help me identify the mistake, that would be great. ...

A JSON request is being processed within a while loop

Attempting to complete what I initially thought was a simple task has led me to believe that I may have oversimplified the process or made a mistake in my loop. My objective is to browse through a series of links containing JSON objects in order to identif ...

Assign the value of a state by accessing it through a string path key within a complexly

I'm currently attempting to modify a deeply nested value in an object by using a string path of the key to access the object. Here is my setup: const [payload, setPayload] = useState({ name: "test", download: true, downloadConfi ...

Unexpected Token E encountered in the Twitter stream.on function

I'm currently in the process of setting up a search button on my web application that will pull all Twitter tweets related to the search input using the streaming API. Below is my client-side code: <form class="navbar-form navbar-left" role="sear ...

Ways to effectively go through local storage using a loop

I'm currently working on enhancing my navbar by adding links based on searches made by users and their favorite selections. My goal is to avoid duplicate entries in the "past searched" section if the current search already exists in the list. I'm ...

Collapsing Bootstrap menu bar causing logo overlap

When the navbar collapses (when it shows the toggle icon), the menu items (home, services, portfolio, about, contact) overlap with the logo. If I remove the position:absolute from the logo (navbar-brand), the menu appears in the center. Is there a way to h ...

Declare the variable as a number, yet unexpectedly receive a NaN in the output

I'm facing an issue with a NaN error in my TypeScript code. I've defined a variable type as number and loop through an element to retrieve various balance amounts. These values are in the form of "$..." such as $10.00 and $20.00, so I use a repla ...

What could be causing one of my images to not appear on my Gatsby page?

Hey there, I could use some help with this issue: Recently, I created a website using Gatsby.js and deployed it to my web server (which is running NGINX on Ubuntu 20.04). The site uses Gatsby Image for querying and displaying images, and everything seems t ...

Ways to retrieve the ID attribute value of the third ancestor above

How can I retrieve the ID attribute of the 3rd parent element when a link is clicked? Take for example: <div id="First Div"> <div class="class A"> <div class="class B"></div> <div class="class C"></div> &l ...