Leverage the JSON data to populate the category axis in c3.js

I have a JSON object that contains an array called datas, which holds the data I need to use for my chart. I want to utilize the data1 array for the x-axis in a category format. How can I achieve this?

This is my attempted solution, where I extract the data from the JSON object into a string:

chart script

   var datas={"data1":["a","b"],"data2":["10","20"]};
                 // this data comes from AJAX
                var out ="";
                for(var i=0;i<datas.data1.length;i++){
                 var out = datas.data1[i];
                
                }
            alert(out);
    var chart = c3.generate({
    bindto: '#chart',
           size: {
            height: 450,
           },
        data: {
            columns: [
             ['data1', 30, 200, 100, 400, 150, 250],
             ['data2', 50, 20, 10, 40, 15, 25]            
                ],
            type: 'line',
            },
            color: {
            pattern: ['#80B5EC', '#2A2A2E', '#FC8D2D', '#3FE51D', '#F51E50', '#F5D81E', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']
        },
            zoom: {
            enabled: true
        },
        axis: {
            x: {
                type: 'category',
                tick: {
                   
                    multiline: false
                },
                
                categories: [out],
                  height: 100
            },y: {
    
                label:{ 
                text:'TASKS',
                position: 'outer-middle'
            }
            }
    
        },
        grid:{
            y:{
                show:true
            }
        }
    });
    
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.8/c3.js"></script>
<div id="chart"></div>

Output of the alert:

a,b  

If I use this var out in the c3.js object, I believe it will appear as "a,b" or ['a,b'].How can I include this value in the c3.js object? Check the output image of the chart here.

Answer №1

Here's a condensed and polished version of your code snippet. You'll notice that within the JSON object, you can directly reference the data1 variable without needing to extract the data.

In your JavaScript for loop, what it did was assign the data1 array's value to a string, triggering the Array.toString() function which concatenated the array elements into a single string. There are numerous resources online demonstrating how to correctly copy arrays. However, in this case, there's no need since you can access the array directly from the JSON object.

EDIT: The example has been updated to better represent a scenario where the data set intended for plotting is provided within the JSON itself. Here, we utilize Array.unshift to prepend the dataset name to the column array.

var data = {"datapts":["a","b","c","d","e","f"], "data1": [30, 200, 100, 400, 150, 250]};

// Array.unshift inserts an entry at the start of an array.
data.data1.unshift('data1');

var chart = c3.generate({
    data: {
        columns: [
         data.data1
        ],
        type: 'line'
  },
    axis: {
        x: {
            type: 'category',
            categories: data.data1
       }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.8/c3.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.8/c3.min.js"></script>
<div class='wrapper'  style='height: 450px;'>
<div id="chart"></div>
</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

The process of deserializing JSON data in VB.Net

I have a JSON data that I need to convert back into objects. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim client As New RestClient(BaseUrl) Dim Respons As Object client.Authenticator = O ...

Knex is requesting the installation of sqlite3, but I am actually utilizing a MySQL database

While attempting to execute a query on my local MySQL database using knex, I encountered an issue where it prompted me to install the SQLite3 driver, even though my database is MySQL. To troubleshoot, I installed the SQLite3 driver to see if it would reso ...

The checkbox is failing to display as checked even after its value has been dynamically set to true

Currently, I am immersed in a project within ASP.NET MVC that involves displaying data on a page where users can interact by selecting checkboxes to make changes. In cases where there are numerous checkboxes present, a "Select all Checkboxes" button become ...

Effective methods for transferring parameters between two separate JavaScript files within an express.js application

Currently, I am working with Express.js and facing a challenge in passing parameters from one JavaScript file to another. How can this be accomplished? The two files involved are 1. process.js var WebPageTest = require('webpagetest'); var wpt ...

angularslideables retro animation

I'm currently using the AngularSlideables library to toggle a modal within my Ionic project. You can check out a functional example in this fiddle: http://jsfiddle.net/3sVz8/19/ However, I am facing an issue where the initial height is set to 100% i ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...

Is there a way to ensure a function is only executed once whenever the page is refreshed?

I have the following code snippet: function myfunc () { alert('executed'); } $('.classname').on('click' function () { myfunc(); }); I am trying to ensure that myfunc is only executed once. I don't want it to ru ...

Storing data on your local machine using Electron

I am in need of help with my template files which have variable strings. I want to create a basic input form using Electron (https://www.electronjs.org/) and save the resulting output file on the user's device. Could someone recommend a module that e ...

Developing a custom JsonMediaTypeFormatter for a Webapi platform

I'm currently working on developing a custom JSONMediaTypeFormatter to send some JSON parameters to a web API endpoint. The goal is to encrypt the data returned from the web API, which requires creating a customized media type formatter. Within my we ...

Whenever I navigate to this specific route, I consistently encounter an error message in my console

VM28353:1 Error: Unexpected token 'o' found in JSON at position 1 at JSON.parse (<anonymous>) at getUser (auth.js?c7d4:11) at wrappedGetter (vuex.esm-browser.js?5502:335) at Object.eval [as getUser] (vuex.esm-browser.js?5502 ...

Sending data from a JavaScript variable to PHP within the same page

I've been attempting to transfer a JavaScript variable to PHP within the same page without success. I have tried different codes but none seem to be working as expected. Here is the current code snippet: function init(e){ $('#DeleteDaily' ...

Determine the number of rows in an Ajax-fed datatable (including paginated rows) that have a specific value in a

I am struggling with counting rows in #datatableOne where the 'Status' column has a value of 'Unknown'. I have attempted a couple of solutions, but they are not giving me the desired results. The first solution only counts the rows on ...

Having trouble getting Vue.js data to show up on the screen. I'm attempting to show a list of todos, but all that

I'm currently working on my App.vue file where I have set up the data for a todo list. However, despite creating an array of todos and attempting to display them, nothing is showing up on the screen. I'm at a standstill and could really use some ...

Is my $.getJson function triggering another action in my project involving adding items to the cart?

Here is my code in the view page: <form method="post"> <input id="Submit1" type="submit" value="Deleteallcarts" /> </form> <input type="submit" class="product_btn" value="Buy Now" /> <script type="text/javascri ...

Can you provide some instances of online services that use basic authentication?

Is there a website out there that offers web services requiring simple username and password verification? I'm open to any type of service: SOAP, REST, JSON, XML, etc. I need this for testing purposes, but it seems like most web APIs nowadays are ei ...

What is the process for generating an API endpoint in Next.js that includes a query string?

I am currently working on setting up an API endpoint in Next.js, specifically the following one: /api/products/[name]?keyword=${anykeyword}. To accomplish this, I understand that I have to create it within the pages/api/products/[name] directory in index ...

HTML or JS/jQuery can create disorienting cursor behaviors

Is there a way to create a distorted or crooked mouse movement on a webpage, even though the user is moving the mouse normally? I'm exploring ways to simulate the experience of a Parkinson's or arthritic patient trying to navigate a web page wit ...

Converting extensive XML documents into JSON format

Dear team, I am currently working on a project that involves converting large XML files into JSON format. While I have written some code for this task, I'm facing the challenge of slow performance. I've explored options like lxml and BeautifulSo ...

Attempting to store data types such as json, jsonb, hstore, xml, enum, ipaddr, etc. results in an error message indicating that the column "x" is of type json whereas the expression is of type character varying

When PostgreSQL is used to store data in a field with a string-like validated type such as xml, json, jsonb, xml, ltree, etc., encountering an error during an INSERT or UPDATE process is common. The error message might look like this: column "the_col" is ...

Decoding a JSON containing dynamic key-value pairs into an object using C#

Currently, I am utilizing C# .NET 4.0 for the purpose of parsing a JSON data into a personalized object. My approach involves using JavaScriptSerializer.Deserialize to map it to a class that I have designed. The challenge lies in the fact that the name/val ...