Looping through a JSON object in Highcharts to populate data series

I'm brand new to Java Script and I'm on a mission to loop through my JSON object and populate the Highcharts data series. You can take a look at my static demonstration of what I'm trying to achieve on JS Fiddle. Check out JsFiddle here

Any kind soul out there willing to lend me a hand with this?

Below is the JSON object that needs to be iterated through in order to fill the Highcharts data Series.

{
    "OuterKey": {
        "v4_acl": {
            "aggregate": 100,
            "S1": 40,
            "S2": 30,
            "S3": 20,
            "S4": 10
        },
        "v6_acl": {
            "aggregate": 120,
            "S1": 14,
            "S2": 13,
            "S3": 12,
            "S4": 11
        },
        "v4_qos": {
            "aggregate": 125,
            "S1": 30,
            "S2": 14,
            "S3": 17,
            "S4": 19
        },
        "v6_qos": {
            "aggregate": 80,
            "S1": 22,
            "S2": 21,
            "S3": 20,
            "S4": 23
        },
        "v4_nf": {
            "aggregate": 90,
            "S1": 20,
            "S2": 20,
            "S3": 20,
            "S4": 26
        },
        "v6_nf": {
            "aggregate": 111,
            "S1": 11,
            "S2": 44.5,
            "S3": 45,
            "S4": 80.5
        },
        "baseline": {
            "aggregate": 130,
            "S1": 60,
            "S2": 10,
            "S3": 10,
            "S4": 10
        }
    }
}

And here's a snapshot of the statically displayed rendered chart for reference.

https://i.sstatic.net/JxEx9.png

Answer №1

If you're looking to perform a specific transformation, the following code snippet might help:

const raw = {
    "ExampleKey": {
        "categoryA": {
            "aggregate": 100,
            "Item1": 40,
            "Item2": 30,
            "Item3": 20,
            "Item4": 10
        },
        "categoryB": {
            "aggregate": 120,
            "Item1": 14,
            "Item2": 13,
            "Item3": 12,
            "Item4": 11
        },
        "categoryC": {
            "aggregate": 125,
            "Item1": 30,
            "Item2": 14,
            "Item3": 17,
            "Item4": 19
        },
        // More categories and data entries here
    }
};

const transformedData = Object.values(raw.ExampleKey)
  .reduce((memo, v) => { 
    for (s in v) { 
      memo[s] = memo[s] || []; 
      memo[s].push(v[s]); 
    } 
    return memo; 
  }, {});
  
const series = Object.entries(transformedData)
  .map(([name, data]) => ({name, data}));

Highcharts.chart('container', {
    title: {
        text: 'Custom JSON Chart'
    },
    yAxis: {
        title: {
            text: 'JSON VALUE'
        }
    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle'
    },
    xAxis: {
        categories: Object.keys(raw.ExampleKey),
        crosshair: true
    },
    series
});
#container {
min-width: 310px;
max-width: 800px;
height: 400px;
margin: 0 auto
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>

<div id="container"></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

Troubleshooting loading specific story types on hacker news API with Angular.js

I have been working on a hacker news client using the official hacker news firebase API and Angular.js. Everything seems to be working fine except for the 'jobstories' posts, which are not rendering on the screen even though the story IDs are bei ...

Is there a way to extract just the first line or n characters from a JSON file without having to download the entire dataset?

I am looking to extract specific information from a large JSON file that is 450 KB in size. However, I do not need to download the entire JSON file as I only require certain characters or lines from it. Is there a way to read n characters or line by line ...

What could be causing my node server's REST endpoints to not function properly?

Here is a snippet of my index.js file: var http = require('http'); var express = require('express'); var path = require('path'); var bodyParser = require('body-parser') var app = express(); var currentVideo = &apos ...

Execute JavaScript function in NodeJS server background

I have developed a function that periodically monitors the battery statuses of connected android devices and returns an array. How can I execute this function on server startup and ensure it continues to run while sharing its information with other pages? ...

Using `texture.needsUpdate = true` in Three.js can cause significant performance issues due to its slow execution

I am currently working on a project involving a Three.js scene where I need to update textures after a certain period of time. However, I have noticed that updating the textures is causing a significant slowdown in the FPS, dropping it to 1-2 FPS for sever ...

Establishing REST parameters for jQuery to consume a web service

Currently, I am utilizing jQuery to consume a custom-built web service that serializes input into JSON and outputs it via jQuery AJAX. I am interested in enhancing the RESTfulness of the service by incorporating URI query string parameters. This would ena ...

Dynamic field refreshed on server side upon second button press

I'm encountering an issue where a hidden field that I update via Javascript only reflects the new value after clicking a button twice. Surprisingly, I can view the updated hidden field value when inspecting it through the browser. Default.aspx <s ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

The initial click event for the input element in Jquery is not functioning correctly

I found a jQuery date selector online and the script looked something like this... <script type="text/javascript> $(document).ready(function () { $("#date3").click(function() { $("#date3").scroller({ preset: 'datetime' }); wheels = []; whe ...

Code-based document editing with CouchBase

To test Couchbase, I need to create a servlet that will edit 1,000 JSON documents by changing the value of '"flag": false' to '"flag": true'. How can I achieve this task? Here is my view code for finding documents with '"flag": fa ...

Eliminate the use of backslashes in JSON responses when using the WordPress REST API

As I work on extending the Wordpress Rest API, I encounter backslashes even after adding json flags to eliminate them. Below is what I am attempting: stripslashes(json_encode(['success'=> true], JSON_FORCE_OBJECT | JSON_HEX_APOS)); The outpu ...

Inserting data into a table using variables in Mssql database management system

I'm really struggling to find a way to safely add my Variables into an MSSQL server. I've tried everything. Could someone please help me and provide the solution for adding my Variables into the Database? It is crucial that I prevent any possib ...

The $emit method in Vue seems to be ineffective when used on the parent component, yet it functions properly when used on the

I have a component called "register" which contains an event listener @submit.prevent inside the template, and I am using $emit to send the data. When I console.log within the method of the component itself, it works fine. However, when I try to access the ...

When you hit the enter key in a text input field in JavaScript, it triggers a specific function

http://codepen.io/abdulahhamzic/pen/YqMQwB Is there a way to make it so that when I hit the enter key on a text input, it triggers a specific function? I attempted to achieve this using the following code: <input type="text" onkeypress=" ...

Tips for effectively using the JQuery animate function

Displayed below is my implementation of the jQuery animate method abstraction that works well. However, a challenge arises when trying to replace the hard-coded DOM element class in the function ani(){} with the 'this' keyword for versatility acr ...

The function ajax does not recognize response.forEach as a valid function

When I try to use ajax for fetching data from MySQL using PHP and JavaScript, I encounter a function error stating "response.forEach is not a function". Despite looking through various posts on this issue, none of the suggested solutions have been able to ...

Discover the process of incorporating secondary links into your dabeng organizational chart!

I need to incorporate dotted lines on this chart, such as connecting leaf level nodes with middle level nodes. import OrgChart from '../js/orgchart.min.js'; document.addEventListener('DOMContentLoaded', function () { Mock.mock(&apo ...

Is JavaScript utilizing Non-blocking I/O at the operating system level to enable AJAX functionality?

Given that Javascript operates as a single threaded process and AJAX functions asynchronously, the question arises: How does this happen? Is it possible that at the operating system level, the JS engine is responsible for making non-blocking I/O calls fo ...

Struggling with parameter passing issues and preparing code for seamless integration with MYSQL database

I've been dedicating the past four days to a project that I've crafted entirely by hand to test my JavaScript skills as I progress through Codecademy courses. The goal is to develop a browser-based checklist program, and so far, I've success ...

What is the best way to send a request using an API key through a form submission method?

I encountered an issue while attempting to retrieve the json response through a form using the post method; I kept receiving a forbidden 403 error. window.onload = function() { document.getElementById("Save").onclick = function fun() { var x = docum ...