"Utilizing Google Charts DataTable to easily adjust column number based on data dynamics

Struggling with managing JavaScript objects...

Currently, I am working on generating a Google Chart based on user selections. The process involves two multi-select lists that construct an object as shown below:

$('option:selected', $('#slChartSettingsEntities')).each(function () {
    var el1 = $(this);
    $('option:selected', $('#slChartSettingsStats')).each(function () {
        var el2 = $(this);
        dashParms.items.push({
            entityid: el1.val(),
            statid: el2.val(),
            entityname: el1.text(),
            statname: el2.text()
        });
    });
});

The dashParms object is then used to define columns for the chart like this:

// Preliminary setup:

var seriesCount = 0; // I want to optimize this

var data = new google.visualization.DataTable();
data.addColumn({ id: 'date', label: 'Date', type: 'date' });
data.addColumn({ id: result.companyName, label: result.companyName, type: 'number' });
if ($('#cbxEtc').is(':checked')) {
    data.addColumn({ id: 'ave', label: 'Company Average', type: 'number' });
    seriesCount++; // working to improve this
}

// Key aspect:

for (var j = 0; j < dashParms.items.length; ++j) {
    data.addColumn({
        id: (dashParms.items[j].entityid + '#' + dashParms.items[j].statid),
        label: (dashParms.items[j].entityname + ' (' + dashParms.items[j].statname + ')'),
        type: 'number'
    });
    seriesCount++; // working to improve this
}

I send the dashParms to the server and receive back the data (a C# List<List<object>>; detailed demonstration available but not necessary) which is then used to populate the chart rows:

var jsonResult = $.parseJSON(result.chartData);

if (seriesCount == 0) {
    $.each(jsonResult, function (k, v) {
        data.addRow([
            new Date(v[0], 0, 1),
            v[1]
        ]);
    });
}
else if (seriesCount == 1) {
    $.each(jsonResult, function (k, v) {
        data.addRow([
            new Date(v[0], 0, 1),
            v[1],
            v[2]
        ]);
    });
}
else if (seriesCount == 2) {
    $.each(jsonResult, function (k, v) {
        data.addRow([
            new Date(v[0], 0, 1),
            v[1],
            v[2],
            v[3]
        ]);
    });
}
else if (seriesCount == 3) {
    // etc etc etc
}

The process is repeated for configuring the chart object:

if (seriesCount == 0) {
    chartcfg = {
        'chartType': 'ComboChart',
        'options': {
            'seriesType': 'bars'
        }
    };
}
else if (seriesCount == 1) {
    chartcfg = {
        'chartType': 'ComboChart',
        'options': {
            'seriesType': 'bars',
            'series': {
                1: { type: 'line', tooltip: true }
            }
        }
    };
}
else if (seriesCount == 2) {
    chartcfg = {
        'chartType': 'ComboChart',
        'options': {
            'seriesType': 'bars',
            'series': {
                1: { type: 'line', tooltip: true },
                2: { type: 'line', tooltip: true }
            }
        }
    };
}
else if (seriesCount == 3) {
    // etc etc etc
}

Seeking advice on refactoring to dynamically create these objects and avoid excessive conditional statements. The main focus is on 1) creating the array for data.addRow(), and 2) generating the chartcfg JSON object.

Answer №1

To efficiently add the rows and construct the series option within the same loop, utilize the value array for looping through the series.

Start by creating the default config object, then iterate through the json and value array.

var chartcfg = {
  chartType: 'ComboChart',
  options: {
    seriesType: 'bars',
    series: {}
  }
};

$.each(jsonResult, function (k, v) {
  var row = [];
  $.each(v, function (index, value) {
    if (index === 0) {
      row.push(new Date(value, 0, 1));
    } else {
      row.push(value);
      chartcfg.options.series[index] = {
        type: 'line',
        tooltip: true
      };
    }
  });
  data.addRow(row);
});

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

Steps for including an animation class in a div

Is it possible to add the sweep to top blue color animation to the red box using a set-timeout function instead of hover? I tried using the following code but it doesn't seem to be working. Can you help me troubleshoot? setTimeout(function() { $( ...

The JavaScript code is executing before the SPFX Web Part has finished loading on the SharePoint page

I recently set up a Sharepoint Page with a custom masterpage, where I deployed my SPFx Webpart that requires certain javascript files. While the Webpart functions correctly at times, there are instances when it doesn't work due to the javascript bein ...

The Echart bar graph is not displaying when trying to use JSON data

Seeking assistance as a beginner in building Basic Bar inverted axes using json data. I am trying to achieve a chart similar to Bar Inverted Axes, but encountering issues with the chart not displaying properly. Utilizing Angular to develop the web applicat ...

filling out a form with data retrieved through an ajax request

After retrieving JSON data from an MVC controller, I am attempting to populate a form with this data but encountering difficulties. The returned data consists of only one row with three properties. Despite confirming that the data is being returned success ...

AngularJS and PHP - Issue with HTML tags not being decoded properly

I'm currently working on a project using angularJS with a PHP backend and MySQL database. The PHP API is responsible for sending data to the angularJS frontend for display. Unfortunately, I'm facing an issue where HTML tags are not being decoded ...

Using AJAX to send a POST request to a PHP backend server

Is it required to JSON.stringify the POST parameters/request object when making an AJAX POST call to a PHP backend? Can it be sent as a JS object without conversion? How does PHP handle them differently? Are there any recommended best practices for the re ...

Error: The variable 'error' could not be located

Below is the code that I am using: $(document).ready(function(){ var callPage = function(){ $.post('/pageToCall.php'); }; setInterval('callPage()', 60000); }); However, I encountered an error stating ReferenceErro ...

Identify and alert when the download has finished

Imagine having a drive link to download a zip file. Upon clicking the link, the download begins in the browser. After the download finishes, I would like to send an email notification to the user. Is this achievable? I am using a .NET application (C#) wi ...

Calculating JS functions before images are loaded

Following up on a previous question, I am utilizing JavaScript code from another article to position a "content" div relative to a fixed div in my project. However, the issue arises when the positioning of the "content" div is calculated only after all the ...

The issue of NextAuth in connection with Spotify failing to display the user's profile picture

I have recently implemented NextAuth v4 and encountered an issue after authenticating with Spotify. Despite successfully retrieving user information from Spotify, I seem to be missing access to the user's profile picture. Here is the data I receive fr ...

Chrome extension for AJAX with CORS plugin

Currently, I am utilizing jQuery for cross-origin AJAX requests and attempting to include headers in the request as shown below. However, I am encountering an error message stating that it is an invalid request: $.ajax({ url: address, headers:{ ...

Top Method for Reloading Element-Specific JavaScript When Replacing Elements

Is there a better way to re-initialize JavaScript without needing a page refresh? I'm currently struggling with appending an MDBootstrap <select> tag, which involves more than just adding a child element. Instead, I have to remove the element an ...

The message sent from the server via SocketIO seems to be malfunctioning

Currently, I am in the process of developing an application that utilizes websockets for facilitating server-client communication. The main idea behind this concept is to enable the client to request messages from the server, while also allowing the server ...

Encountered an issue when trying to establish a connection to the MySQL database on Openshift using a

I am currently running a Node.js app with Express that is deployed on OpenShift. I have set up databases using the PHPMyAdmin 4.0 cartridge. Although I can establish a connection to the database, anytime I run a query, it throws an ECONNREFUSED error. Whe ...

What is the recognized standard or upcoming JSON format for defining forms and fields?

Lately, I've found myself stepping back from a couple of frameworks and starting fresh. One involves a Javascript-driven form UI, while the other concerns Java Swing. I've come to realize that I can create a straightforward JSON object to define ...

Using jQuery AJAX to send data containing symbols

When making an AJAX call, I am including multiple values in the data like this: var postData = "aid="+aid+"&lid="+lid+"&token="+token+"&count="+count+"&license="+license; postData = postData + "&category="+category+"&event_name="+e ...

What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={bg-[url('${path}')] h-screen bg-cover bg-center text-white border-b-8 border-b-solid border-b-sla ...

Changing the Elements in a Two-Dimensional Array in Python

Hello everyone, I am working with a 2D array that has the following structure: 12381.000 63242.000 0.000 0.000 0.000 8.000 9.200 0.000 0.000 12401.000 8884.000 0.000 0.000 96.000 128.000 114.400 61.600 ...

Tips for incorporating JavaScript modules into non-module files

Learning how to use js modules as a beginner has been quite the challenge for me. I'm currently developing a basic web application that utilizes typescript and angular 2, both of which heavily rely on modules. The majority of my app's ts files ...

"Utilize Jquery to access and interact with a REST API

Exploring the realm of RESTful services has been intriguing. I encountered an issue where creating a class and defining a function within it worked fine, but when calling it through jQuery, it returned null. However, directly typing the URL in the address ...