What is the best way to create dynamic series data for highcharts?

I have integrated angular-highcharts into my project and utilized this column chart from https://www.highcharts.com/demo/column-basic for visualizing my data. Below is the format of my data:

[
    {
        "project": "train project1",
        "hours": {
            "AD": 58265
        }
    },
    {
        "project": "butify",
        "hours": {
            "AD": 3940
        }
    },
    {
        "project": "skler",
        "hours": {
            "AD": 563250
        }
    },
    {
        "project": "Internal Application",
        "hours": {
            "AD": 33325,
            "DAM": 328095
        }
    },
    {
        "project": "train2project",
        "hours": {
            "AD": 137215
        }
    },
    {
        "project": "CELLProje1",
        "hours": {
            "DAM": 488470
        }
    },
    {
        "project": "rangeselector",
        "hours": {
            "AD": 3015,
            "DAM": 71175
        }
    },
    {
        "project": "Android dev",
        "hours": {
            "AD": 99160
        }
    },
    {
        "project": "Web Application",
        "hours": {
            "AD": 72720
        }
    }
];

The values inside "hours" may be one or more. I have shared a fiddle where I have been attempting to format the JSON for the series data. Additionally, I am trying to construct the X-axis array for the graph:

categories: [
            'train project1',
            'beautify',
            'skler',
            'Internal Application',
            'train project2',
            'rangeselector',
            'Android',
            'Web Application'

        ],

Am I formatting the X-axis correctly?

http://jsfiddle.net/harifrais/uxpvs8fw/34/

Answer №1

If you want to format the data in a specific way, follow these steps:

[ 
    {
       name:"series-name",
       data:[ ... ]
    }
]

In order to use categories effectively, each series must have the same number of elements as there are categories. Since not all hours elements contain the same data, additional work is required.

  1. Create a list of unique keys from hours
  2. Iterate through each element and treat it as a category using the project
  3. Insert zeros where missing elements are found in hours

You can achieve this with a simple 2-step process using reduce and map.

var data = [{"project":"train project1","hours":{"AD":58265}},{"project":"butify","hours":{"AD":3940}},{"project":"skler","hours":{"AD":563250}},{"project":"Internal Application","hours":{"AD":33325,"DAM":328095}},{"project":"train2project","hours":{"AD":137215}},{"project":"CELLProje1","hours":{"DAM":488470}},{"project":"rangeselector","hours":{"AD":3015,"DAM":71175}},{"project":"Android dev","hours":{"AD":99160}},{"project":"Web Application","hours":{"AD":72720}}];

// get a distinct list of hour keys
var seriesData =  data.reduce( (acc, {hours}) => {
     Object.keys(hours).forEach(key => {
        if(!acc[key]) acc[key] = [];
    })
    return acc;
},{});

// reduce the original data to get categories and series values
// filling in zeros where necessary
var result = data.reduce( (acc, {project,hours}) => {
   acc.categories.push(project);
   
   Object.keys(acc.seriesData).forEach(s => {
       acc.seriesData[s].push(hours[s] || 0);
   });
   
   return acc;
},{categories:[],seriesData:seriesData});

// shape the data to how highcharts wants it
var categories = result.categories;
var series = Object.entries(result.seriesData).map( e => ({
    name: e[0],
    data:e[1]
}));

console.log(categories);
console.log(series);

To see the results in a fiddle for highcharts/your data, check out this link: https://jsfiddle.net/u7opL2dw/2/

Answer №2

Check out my approach on how to utilize your data with the Highcharts library, regardless of the number of properties present in the data.hours object.

Take a look at the demonstration: http://jsfiddle.net/UniquelyCoded/7h29sm4t/

const categories = sampleJson.map(data => data.project);

const getSeriesNames = sampleJson.map(data => {
    for (let i in data.hours) {
        return i
    }
}).filter((item, i, ar) => ar.indexOf(item) === i);


const series = getSeriesNames.map(name => {
    let output = {
        name: name,
        data: []
    };

    sampleJson.forEach(data => {
        if (data.hours[name]) {
            output.data.push(data.hours[name])
        } else {
            output.data.push(null)
        }
    });
    
    return output
})

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

Learn the process of transmitting JSON data from a server-side (nodejs) to the client-side using Ajax

I have successfully set up a Node.js/express server to make a GET call to an API, which returns JSON data. Now, I am looking for ways to send this JSON data to my local JavaScript (client-server) in order to manipulate it by looping through and appending i ...

Discovered a few JSON logical operators within a Chat API - curious to learn how they operate

In the process of incorporating a user chat feature into my personal project, I came across an API that includes the following JSON code snippet. While I can identify it as JSON, I'm struggling to fully comprehend its functionality. Can someone please ...

Optimal Approach: Utilizing Python3 to Parse Facebook JSON Data into MongoDB

I am currently exploring the most effective method to parse Facebook JSON responses into MongoDB. Sample FB Event JSON: { "description": "Event description", "name": "Event name", "place": { "name": "Place name", "location": { "city": ...

What is the best way to have two div elements scroll simultaneously?

Is there a way to synchronize scrolling between two divs? I have a situation where one div is larger than the other, and I want them both to scroll together. Any suggestions? .content { width: 100%; } .left { background-color: yellow; width: 50%; ...

The affluent text editor's input field fails to retain information

Currently, I am facing an issue with my HTML page. When using a plain HTML textarea, the pre-set options work fine. However, when switching to a rich editor, the textarea stops holding data as expected. Please refer to the demo pages for clarification. Pa ...

Alerts are essential for the proper functioning of the AJAX function. Without them

As I incorporate a substantial amount of AJAX with XML Http Requests on my website, I encounter a peculiar issue with a few random AJAX calls. There seems to be an execution problem within my JavaScript code in the onreadystatechange function where certain ...

adding SVG elements inside a DOM element using SnapSVG

After successfully loading and appending multiple SVGs to a DOM element, I encountered an issue when trying to do the same with only one SVG file. When attempting to extract nodes using: let myElement = fragment.select( '#elementID' ); container ...

Leverage Java variables within JavaScript

Currently encountering an issue with integrating a java variable (obtained from a database record) into JavaScript for the datePicker UI. The goal is to assign the java variable to the javascript var "unavailable" so that already booked dates become unclic ...

"What is the purpose of using the `position: absolute` property for movement transitions while deleting an item from a list

Click here to see an example where items smoothly move in a list when one item is removed. To achieve this effect, the element needs to be styled with: .list-complete-leave-active { position: absolute; } I'm curious as to why it doesn't work w ...

What is the best way to retrieve $_SESSION variables following an Ajax request?

My website has a login feature where users can enter their credentials and the login request is sent using jQuery's $.ajax to a processing page. During the login attempt, any errors that occur are collected and stored in $_SESSION['error']. ...

Unlocking Controller Functions in AngularJS Directives: A Step-by-Step Guide

Here is a sample controller and directive code: class DashboardCtrl { constructor ($scope, $stateParams) { "ngInject"; this.$scope = $scope; this.title = 'Dashboard'; } loadCharts () { // some logic here } } export def ...

Navigate through two distinct elements by categorizing them based on their types

After completing the frontend design, I moved on to integrating the backend and encountered an issue. If anyone can offer assistance or even a hint, it would be greatly appreciated. Visit the demo website for more insight. Initially, I hard coded the comp ...

An error was encountered while linting /app/layout.tsx at line 16: Rule "@typescript-eslint/no-empty-function" was violated due to inability to read properties of undefined (reading 'getTokens')

I am puzzled as to why the function that generates JSX is being checked by the "next lint" script with the rule "@typescript-eslint/no-empty-function". The code snippet at line 16 of the layout.tsx file looks like this: export default function RootLayout( ...

The result returned by Restkit after sending a postObject request

I have successfully posted to my rails server using the post object method. [manager postObject:recipe path:@"/api/recipes" parameters:@{ @"auth_token": fbAccessToken } success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { ...

Utilizing a mutual RxJS subject for seamless two-way data binding in Angular 2

I have a unique service dedicated to managing app configurations class Configuration { get setting() { return dataStore.fetchSetting(); } set setting(value) { dataStore.saveSetting(value); } } This configuration is linked to components t ...

implement a dropdown feature for a vertical menu with the help of Jquery

Struggling to implement a dropdown feature on a vertical navigation using Jquery. The HTML includes a nav section with 1st level list items and nested li's for second level menu items. On clicking the 1st level li, the intention is to toggle SHOW/HID ...

JSON conversion error: Unable to convert circular structure to JSON - locate problem within JSON structure

Currently, I am utilizing Contentful in conjunction with a MEAN stack. Upon querying the Contentful API, I receive a json object. contentClient.entries(query, function(err, entries){ if (err) throw err; console.log(entries); }); Lately, I have been e ...

An error of type `TypeError`: attempting to call `[0,1]` as a function arises while using an IIFE

Check out the following code: var numberArray = [0, 1] (function() { numberArray.push(2) function nestedFunction() { numberArray.push(3) function anotherNestedFunction() { numberArray.push(4) } console.log(num ...

Utilizing nested JSON data with React

Hey there! I've been working on adding more levels in Json pulled from Mongo, but I'm running into an issue with accessing elements that have multiple levels of nesting. It seems like it can't read the undefined property. Is there a limit t ...

Experiencing the power of DoJo with the latest Wordpress 4

SOLUTION: After some investigation, I discovered that reordering the loading sequence of jQuery UI and DoJo files in the footer resolved the issue. By placing jQuery UI before any DoJo-related files, I ensured jQuery UI was fully loaded before any DoJo scr ...