Using a for loop in Flot to display data from a JSON file

I am working on creating a dynamic flot graph that will adjust based on the data provided. The information for my flot graph is in JSON format, and here's an example of the dataset:

{
    "total":[[1377691200,115130],[1377694800,137759],[1377698400,137759],[1377702000,137759],[1377705600,137759],[1377709200,139604],[1377712800,137759],[1377716400,137759],[1377720000,137759],[1377723600,137759],[1377727200,137759],[1377730800,138156],[1377734400,137759],[1377738000,137759],[1377741600,137759],[1377745200,137759],[1377748800,138156],[1377752400,137759],[1377756000,137759],[1377759600,168831],[1377763200,137759],[1377766800,0],[1377770400,0]],
    "dev0":[[1377691200,115130],[1377694800,137759],[1377698400,137759],[1377702000,137759],[1377705600,137759],[1377709200,139604],[1377712800,137759],[1377716400,137759],[1377720000,137759],[1377723600,137759],[1377727200,137759],[1377730800,138156],[1377734400,137759],[1377738000,137759],[1377741600,137759],[1377745200,137759],[1377748800,138156],[1377752400,137759],[1377756000,137759],[1377759600,168831],[1377763200,137759],[1377766800,0],[1377770400,0]],
    "dev1":[[1377691200,0],[1377694800,0],[1377698400,0],[1377702000,0],[1377705600,0],[1377709200,0],[1377712800,0],[1377716400,0],[1377720000,0],[1377723600,0],[1377727200,0],[1377730800,0],[1377734400,0],[1377738000,0],[1377741600,0],[1377745200,0],[1377748800,0],   [1377752400,0],[1377756000,0],[1377759600,0],[1377763200,0],[1377766800,0],[1377770400,0]]
}

Here is the script I have developed so far:

$(".bytes_portal_pop").click(function(e) {
    e.preventDefault();
    var graph=$(this).data('graph');
    var range=$(this).data('range');
    var divid=$(this).data('divid');
    var title=$(this).data('boxtitle');

    $.getJSON("/action/sites/GetFlotStats/?graph=" + graph + "&range=" + range, function(json) {           
       //success - data loaded, now use plot:
       var plotarea = $("#" + divid);               
       var dev0=json.dev0;
       var dev1=json.dev1;          
       $.plot(
            $("#" + divid), 
            [
                {
                    data: dev0,
                    lines:{show: true, fill: true},
                    label: "dev0",
                },
                {
                    data: dev1,
                    lines:{show: true, fill: true},
                    label: "dev1",
                },

            ],                
            {
                xaxis: {mode:"time"},
                grid: {hoverable: true},
                tooltip: true,
                tooltipOpts: {
                    content: "Traffic: %y GB"
                }
            }
       );
    });

$("#boxtitleB_flot").html(title);
});

Currently, this method works well and displays the two lines as needed. However, I would like to make it more dynamic so that I don't have to manually define each graph line. I believe I can achieve this by implementing a for or each() loop on the "var dev0=json.dev0;" and the code block below it.

Any assistance in achieving this dynamic functionality would be greatly appreciated.

Answer №1

Yes, the best approach is to create a dynamic loop for generating series objects.

Imagine you have a JSON response that looks like this:

jsonData = {
    "total":[[1377691200,115130],[1377694800,137759],[1377698400,137759],...],
    "dev0":[[1377691200,115130],[1377694800,137759],[1377698400,137759],...],
    "dev1":[[1377691200,0],[1377694800,0],[1377698400,0],...]
};

You can then create an array of series as follows:

var series = [];
$.each(jsonData, function (key, val) {
    var serie = {};
    serie.label = key;
    serie.data = val;
    series.push(serie);        
}); 

Finally, display the plot using the following code:

$.plot(
   $("#placeholder"), 
   series, 
   {}
 );

Check out the live example on JSFiddle.

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

Executing a function when a specific element is triggered within an ng-repeat in AngularJS

Hey there, I've been grappling with changing the limitTo filter on a specific list, but I'm encountering an issue: whenever I trigger the filter change, it applies to all ng-repeated categories. The function within my main controller is as foll ...

Create a JavaScript function that adds cells to a table, each containing an input field and a corresponding

I successfully developed a function that appends a table with rows and cells, then fills those cells with data from an array. However, I am now faced with the challenge of modifying it so that the generated cells contain an input field where the value= att ...

"Implementing filtering logic for an array of objects with multiple conditions in a React application

I am looking to apply filters to a person list based on criteria such as city, job, age, and gender. How can I apply filters based on five conditions in React? I tried using filter chaining but it did not work for me. In the useEffect hook, I applied indiv ...

Delete property from object in JavaScript

Looking for a solution to replace the content of an object with another in an array of objects without passing the reference directly. The challenge is not knowing what values my function will pass, so I can't use them as keys to avoid copying the re ...

Conceal a specific class from being seen by another class of the same name upon clicking

I have a webpage with multiple images all sharing the same class name. When I try to hide a specific image by clicking on it, all images with that class are affected. Even though I used PHP to display the images on the webpage, I haven't been able to ...

Step-by-step guide on validating a user in Joomla using AJAX and jQuery

Is there a way to authenticate a user in Joomla through an AJAX call? I want to implement an error effect if the login is incorrect and redirect the user upon successful authentication. I am specifically interested in using JQuery's .ajax API for thi ...

Having trouble downloading the Chip component in Material-UI? Learn how to fix the download issue

I used the UI to upload a file, and now I want to download it either after some time or instantly. I tried implementing this using the <Chip> component, but it's not working. I need assistance in resolving this issue. Uploaded File: const data ...

Create efficient images using Node.js and express using sharp or canvas

Struggling with optimizing image rendering using node, express, and sharp. Successfully implemented an upload method with Jimp for images over 2000px wide and larger than 2mb in file size. While many libraries can achieve this, Jimp was more memory-effici ...

Error message: Angular encountered a SyntaxError when parsing JSON data due to an unexpected character at the beginning of the data

Encountering SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data After validating the JSON, it was discovered that the error lies in: let json = JSON.stringify(user); let params = "json="+json; // The error se ...

Is it possible to utilize a variable from a Higher Order Function within a different generation function?

I am facing a dilemma with the need to utilize email = user.email in newcomment['comments/'+id] = {id,comment,email,date}. However, I am unable to incorporate email = yield user.email or yield auth.onAuthStateChanged(user => {email = user.em ...

Having trouble with Gridview error while trying to retrieve data from json. Any suggestions on how to troubleshoot

I've designed a unique gridview with one image view and two text views. The data for the first text view is manually entered, while I plan to populate the second text view using JSON. However, if there is no data present in the JSON text (textview2), ...

Mobile App Feature: Implementing a Recycler View in Android with Accept and Decline Buttons for Request Management via Rest API

Currently, I am working on developing an Android application that relies on Rest API remote data. In this project, I have integrated a RecyclerView with 2 buttons - Accept and Decline - attached to each row within the RecyclerView. The objective is to modi ...

Exploring the usage of slots in WebComponents without relying on shadow DOM

I am working on developing a WebComponent without utilizing ShadowDOM. So far, everything has been going smoothly. However, I now aim to create a component that wraps other components similar to how it is done in Angular with @ViewChild / @ViewChildren. (I ...

Retain the contents of the shopping cart even when the page is refreshed

For a course project, I am recreating a grocery store website and need assistance on how to retain the shopping cart values even after refreshing the webpage. Please inform me if more information is required... <button type="button" id= ...

The nested object was not found in the Gson return

Trying to figure out a basic implementation in my code. I have a json file that I need to read and convert into a Java object using gson. However, I'm encountering an issue where it returns null for nested objects. Json: { "results": { ...

Steps for disabling and collapsing an individual header on the JQuery Accordian

Looking to adjust the behavior of 4 headers in accordions? Specifically, you want to collapse and disable only the first header out of the set. Here's how: $("#ExpandCollapse").accordion({ active: false, collapsible: true }); To ...

Styling does not affect an Angular component that is injected into an iframe

I am facing an issue with styling in an iframe when trying to append my own angular component. Despite various attempts, I have been unsuccessful in getting the styling to apply to the component within the iframe. Upon loading the iframe, I use JavaScript ...

Displaying the URL and title in a TextView after parsing JSON data

I am having an issue with json/android parsing. I am trying to parse data from my database to an android textview using json. However, it is displaying the URL and title as well. Is there a way to hide this or modify the code to prevent it from showing? I ...

react-intersection-observer is specifically designed to function with the final elements

I am currently working on implementing the Lazy Loading feature using react-intersection-observer. The main objective is to load images in the boxes only when they appear within the viewport. At the moment, as I scroll down to the last elements, all the i ...

Using an object as a parameter in a NodeJS function

This past week, I encountered a challenge that has been difficult to overcome. I've been attempting to pass a JSON object as a parameter in a function, but I keep receiving an error message stating that it's not possible. Unfortunately, I don&apo ...