Generate Highchart Column Using JSON Data

I am currently working on a project that requires me to create a column chart using Highchart. To populate the data, I am utilizing $.ajax and the JSON data structure I have looks like this:

[{
    "city": "Tokyo",
    "totalA": "10",
    "totalB": "15"
},
{
    "city": "Seoul",
    "totalA": "20",
    "totalB": "27"
},
{
    "city": "New York",
    "totalA": "29",
    "totalB": "50"
}]

I would like my resulting JSON string to follow this format:

[{
"name": "city",
"data": ["Tokyo", "Seoul", "New York"]
}, {
"name": "totalA",
"data": [10, 20, 29]
}, {
"name": "totalB",
"data": [15, 27, 50]
}]

Your guidance on achieving this outcome is greatly appreciated. Thank you.

Answer №1

Assuming all the elements share the same structure (having identical fields): Check out this Live Example

// src is the source array
// Retrieve the fields from the first element
var fields = Object.keys(src[0]);

// Map each key to...
var result = fields.map(function(field) {
    // Extract data from the original source array
    var data = src.reduce(function(result, el) {
        // Create an array of data
        return result.concat(el[field]);
    }, []);
    // Format the data as desired
    return {name: field, data: data};
});

console.log(result);

If the elements have different structures, the code becomes a bit more complex: View the Live Example here

// Determine the fields by iterating through all elements
// Add keys not yet encountered to an array
var fields = src.reduce(function (fields, current) {
    return fields.concat(Object.keys(current).filter(function (key) {
        return fields.indexOf(key) === -1;
    }));
}, []);

var result = fields.map(function (field) {
    // Another step required here to filter out elements
    // lacking the specific field we're interested in
    var data = src.filter(function (el) {
        return !!el[field];
    })
    // Proceed with the steps mentioned above.
    .reduce(function (result, el) {
        return result.concat(el[field]);
    }, []);
    return {
        name: field,
        data: data
    };
});

console.log(result);

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

javascript implement a process to iteratively submit a form using ajax

I have a dynamic form with an unknown number of input fields that are not fixed. While searching for solutions, I came across jQuery ajax form submission which requires manually constructing the query string. In this scenario, the number of input fields ...

Showing Nested Arrays in Angular 2

If I have an array with image links as shown below, how can I display them in HTML? array = [ { img: [ {0: 'http://hairsalonfurniture.eu/wp-uploads/750x480_how-to-create-a-nice-hair-salon-s-reception-gjzd.jpg',}, {1: 'http ...

How do I check the value of a JavaScript variable in an XSL choose statement?

Currently, I am working with an xsl file in SharePoint and have implemented an xsl choose statement to conditionally display records from my xml. In the code snippet below, I am testing DAS_ID to determine if it is equal to *someValue*. While hardcoding a ...

Display the duplicated values of an array extracted from a JSON object just once

Having some trouble creating a list from json data, you can check out the example. My goal is to display each value only once if duplicates occur (for example, if there are 2 Martini glasses, I only want one to appear in the list), while still preserving t ...

When using Next.js, importing multiple components from the index manifest will automatically import everything

CONTEXT: For a project, I have organized all my UI components in a /components directory. Currently, I export each component in its own file using the following format: export function Component1() { ... } and then import them individually into my page li ...

I'm experiencing issues with my AJAX as it fails to post or respond after the user clicks on the submit

I am currently working on implementing a list of events, each with a tick box and an x box for marking the event as complete or deleted. The challenge I'm facing is that when I click the buttons, nothing happens without refreshing the page. I suspect ...

Updating the load context variable in Django template after making changes via an AJAX call: a step-by-step guide

Here is the code snippet for displaying table items in my customer_items.html page: <table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"> <thead> <tr> ...

`How can I update a textbox's value using JQuery Ajax?`

Currently in the process of implementing an ajax call to update the value of a textbox: <div id="PNIncrementDiv" style="position:absolute; left: 730px; top: 15px; width: 350px;" class=""> <input id="TBIncrementTextBox" class="textbox" type="te ...

Interpret data from an external JSON file into a HighCharts chart using JavaScript

Currently, I am exploring the process of incorporating HighCharts Chart data directly within the actual webpage. Below is the complete code snippet: <!DOCTYPE html> <html><head> <script type="text/javascript" src="http://code.jquery. ...

How to Utilize ngIf and ngFor Together in Angular 4 for the Same Element in ngFor

Just starting with Angular 4 and experiencing a roadblock in my code. Here is the snippet of my code: JSON: [{"name": "A", "date": "2017-01-01", "value": "103.57"}, {"name": "A", "date": "2017-01-08", "value": "132.17"}, ...

What is the reason for the denial of JSON permission within a Linux user's account?

Encountering issues with Laravel installation on Ubuntu 18.04 [ErrorException] Unable to create file (./composer.json): Permission denied ...

Guide to making a fully interactive JSONObject

I am facing a small challenge. I have written a code that involves creating objects from JSONObject and adding data to them in a specific structure, as shown below: JSONObject outerObject = new JSONObject(); JSONArray outerArray = new JSONArray(); JSONOb ...

What is the best way to arrange the information in JSON in ascending order and display it in a table format?

I am working with a mat-table and have used GET to display my data. I now want to sort the data in ascending order based on the db-nr from my JSON. Here is an excerpt from my JSON: { "period": 12.0, " ...

Enter a keyword in the search bar to find what you're looking

I am working on a form where users can select their occupation from a list that is stored in a separate .js file. The list includes various occupations like 'AA Patrolman' and 'Abattoir Inspector'. var occupationSelect = "<select id ...

No receiving an AJAX reply

After stumbling upon a tutorial, I decided to experiment with AJAX to tailor it to my PHP code. The tutorial focused on creating a "like" button functionality, and I managed to incorporate it into my code successfully, updating the total "like" count in th ...

Tracking every AJAX call initiated by JQuery within the WooCommerce platform

Is it possible to track and monitor all Ajax requests invoked through JQuery on WooCommerce? I am currently attempting to identify the specific Ajax action on the WooCommerce cart page that occasionally triggers an endless loop on my WordPress site. ...

What is the process for eliminating transparency from the overlay feature while utilizing Dojox/Standby?

Currently, I'm using a spinner image to indicate loading while retrieving data from the backend. However, the spinner widget creates a translucent overlay over the control. Is there a way to disable this translucency so that only the spinner is visibl ...

The ElasticClient encountered a problem while verifying the connection status

I am currently attempting to verify the status of a connection, but encounter an error during the check. var node = new Uri("http://myhost:9200"); var settings = new ConnectionSettings(node); ElasticClient client = new ElasticClient(settings); ISt ...

The methods $.get() and $.ajax() in jQuery are failing to retrieve data from PHP

I've been trying to use a script to display a message from a PHP file after a click event, but I've run into issues with both jQuery $.get() and $.ajax(). With $.ajax(), I get an alert with an empty message, while $.get() alerts "null". load.php ...

`Even though I specified `{cache: $templateCache}` in the $http call, the directive is still showing $templateCache as

I have two HTML pages named snippet1.html and snippet2.html. I want to use them within my directive in order to add multiple templates using a single directive. To achieve this, I initially tried adding the HTML templates within <script> tags and as ...