How can I extract the return value of a JSON object and store it in a variable?

I am attempting to develop a dynamic chart by utilizing data retrieved from a function housed inside a JSON object.

The JSON object is fetched through the Relayr Javascript API, and looks like this:

relayr.devices().getDeviceData({
            token: toke,
            deviceId: Candle1_deviceId,
            incomingData: function (data) {
                console.log(data.readings[0].meaning);
                console.log(data.readings[0].value);
                return data.readings[0].value;
            }
        });

My objective is to incorporate data.readings[0].value into the chart as shown below:

window.onload = function () {

        var dps = []; // dataPoints

        var chart = new CanvasJS.Chart("chartContainer", {
            title: {
                text: "Westminster Cathedral Building Movement Data"
            },
            data: [{
                type: "line",
                dataPoints: dps
        }]
        });

        var xVal = 0;
         var yVal;
        var updateInterval = 100;
        var dataLength = 500; // number of dataPoints visible at any point

        var updateChart = function (count) {
            count = count || 1;

            for (var j = 0; j < count; j++) {
                yVal = yVal + relayr.devices().getDeviceData.incomingData;
                dps.push({
                    x: xVal,
                    y: yVal
                });
                xVal++;
            };
            if (dps.length > dataLength) {
                dps.shift();
            }

            chart.render();

        };

        updateChart(dataLength);

        
        setInterval(function () {
            updateChart()
        }, updateInterval);

    }

The code above is adapted from an example on CanvasJS.

Answer №1

There's no need to constantly regenerate the chart or set up a separate timer for updating it. Simply update the chart whenever new data is received from relayr by following these steps:

var yVal = 0, xVal = 0, dataLength = 500;
var dps = []; // collection of dataPoints

var chart = new CanvasJS.Chart("chartContainer", {
    title: {
        text: "Westminster Cathedral Building Movement Data"
    },
    data: [{
        type: "line",
        dataPoints: dps
    }]
});
relayr.devices().getDeviceData({
    token: toke,
    deviceId: Candle1_deviceId,
    incomingData: function (data) {
        console.log(data.readings[0].meaning);
        console.log(data.readings[0].value);
        yVal = data.readings[0].value;
        dps.push({
            x: xVal,
            y: yVal
        });
        xVal++;

        if (dps.length > dataLength) {
            dps.shift();
        }
        chart.render()
        return data.readings[0].value;
    }
});

Answer №2

Implement an additional function that takes a value parameter to create your chart:

function generateChart(value) {
    // Handle the provided value

    var dataPoints = [];

    var chart = new CanvasJS.Chart("chartContainer", {
        title: {
            text: "Westminster Cathedral Building Movement Data"
        },
        data: [{
            type: "line",
            dataPoints: dataPoints
    }]
    });

    var xValue = 0;
     var yValue;
    var updateInterval = 100;
    var dataLength = 500; // Number of visible dataPoints at any given time

    var updateGraph = function (counter) {
        counter = counter || 1;

        for (var k = 0; k < counter; k++) {
            yValue = yValue + relayr.devices().getDeviceData.incomingData;
            dataPoints.push({
                x: xValue,
                y: yValue
            });
            xValue++;
        };
        if (dataPoints.length > dataLength) {
            dataPoints.shift();
        }

        chart.render();

    };

    // Generate initial set of dataPoints
    updateGraph(dataLength);

    // Update chart periodically 
    setInterval(function () {
        updateGraph()
    }, updateInterval);

}

Invoke the function outside the callback:

window.onload = function () {
    relayr.devices().getDeviceData({
        token: token,
        deviceId: Candle1_deviceId,
        incomingData: function (info) {
            console.log(info.readings[0].meaning);
            console.log(info.readings[0].value);
            generateChart(info.readings[0].value);
            return info.readings[0].value;
        }
    });
}

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

Tips for updating the minimum value to the current page when the button is pressed on the input range

When I press the next button on the current page, I want to update the value in a certain way. https://i.stack.imgur.com/XEiMa.jpg I have written the following code but it is not working as expected: el.delegate(".nextbtn", "click", f ...

What is the best way to calculate the total duration (hh:mm) of all TR elements using jQuery?

I currently have 3 input fields. The first input field contains the start time, the second input field contains the end time, and the third input field contains the duration between the start and end times in HH:mm format. My goal is to sum up all the dur ...

The Response type does not include a property named 'results'

While working on an application that gathers data from last.fm using angular2, typescript, and firebase, I encountered a coding challenge. To view the source code, visit: https://github.com/vtts/mytunes QUERY: How can I convert the results obtained from ...

Using AngularJS to show content based on a callback function

I'm a beginner in angular and it seems like I might be overlooking something. For the registration form, I need users to provide their location. Depending on whether they allow/support navigator.geolocation, I want to display a drop-down menu for cho ...

Evolution of the material through a fresh new slide

Can someone assist me with an animation issue? I have a slideshow consisting of 4 images that are supposed to transition automatically after a set time interval. Upon initially loading the webpage, the animation works perfectly as intended. However, subs ...

Using single quotation marks in Javascript

When the variable basis contains a single quotation mark, such as in "Father's Day", I encounter an issue where the tag is prematurely closed upon encountering the single quotation mark. 'success' : function(data) { div.innerHTML = &apo ...

Error message states: "An error occurred while attempting to parse the json file

Currently enrolled in the Python Mega Course on Udemy, I'm diligently following the instructions to code all the recommended applications. However, while working on Application 2 - Creating Webmaps with Python and Folium, I encountered the following e ...

Improprove the Express Router in a Node.js application

Is there a way to avoid repeating the isUserAuth and isAdminAuth middleware on each endpoint? Can I apply them just once so they work for all routes without having to specify them individually? const { createBranch, getAllBranch, getBranch } = require(&apo ...

Display HTML components depending on an object's property using AngularJS

Here is the code I have created to display a simple drop down list: var products = [ { "id": 1, "name": "Product 1", "price": 2200, "category": "c1" }, { "id": 2, "name": "Product 2", "p ...

When using Next JS with StoryBook, an error may occur if styles are written in a module.scss file

Every time I try to add some styles to my ButtonWidget.scss file, I encounter an error in the console when running the command yarn storybook Error Code: ERROR in ./src/components/ButtonWidget/ButtonWidget.module.scss 1:0 Module parse failed: Unexpected ...

What potential issues arise from utilizing useRef alongside useSelector?

Although I have the capability to access the store by using thunks and/or global stores, I avoid binding my component to the Redux store. This is because the component will be utilized with various stores both inside and outside of the project. The compone ...

disable full page scrolling on iOS devices

Can you achieve elastic scrolling for a single absolutely positioned div in Mobile Safari without causing the entire page to move up and down? Check out this basic example that illustrates the problem: <!doctype html> <html> <head> ...

Using JSON data with UITableView in an IOS Objective-C application

I'm a novice in Objective-C and I'm facing some challenges with getting JSON data from a URL API into UITableView. Below is the code snippet for my view controller where I'm encountering errors. I'm looking for guidance on what approac ...

Is there a way to detect when a Bootstrap Alert is displayed?

I am using a flask app that flashes messages to an HTML file. When these flashed messages are caught, they are displayed as a bootstrap alert. Here is an example: {% with messages = get_flashed_messages() %} {% if messages %} {% for message in mes ...

Choose a specific inner div element within another div using jQuery

Trying to target a specific div within another div in my HTML structure. Here's how it looks: <div id="Stage_game_page1"><div id="cube0">[...]</div><div id="cube1">[...]</div></div> I am attempting to select #cube ...

Update a nested object key by concatenating key names with "." to create a string

Imagine having this specific object structure: var obj = { level1 :{ level2: { level3: { title: "champion" } } } } Now the goal is to update the title key using a provided string (note that it's a string, not an actua ...

Instructions on converting Dart to JavaScript for a non-web platform

I am interested in compiling Dart to JS for a non-web target, such as fermyon/js or node How can I compile Dart to JS for a non-web target? Update: I have been informed that it is possible, and although I couldn't find specific documentation, there ...

Updating content with jQuery based on radio button selection

Looking for assistance with a simple jQuery code that will display different content when different radio buttons are clicked. Check out the code here. This is the HTML code: <label class="radio inline"> <input id="up_radio" type="radio" n ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

Sending a string data from client to a MongoDB database using Express.js and Node.js with the help of Sails framework

Need help with sending a string from client to mongoDB using Sails The "val" variable represents a string sent in real time from the client to the server database POST Form( is using HTML the best approach here? ) <!DOCTYPE html> <html> < ...