Ways to retrieve elements from a JavaScript array?

I have made an AJAX call that retrieves data in the form of an array structured as shown below:

{
“periodStart” : “2016-10-09T06:00:00Z", 
“periodEnd":"2016-10-16T06:00:00Z",
“nextPageStart":null,
“prevPageStart":"2016-10-02T00:00:00Z",
“period":"WEEKLY",
“powerInfo":null,
“totalSavings":
5.8863351343078,

“savings”:[
{
“maxTemperature":75,
“acRunSeconds":16432,
“savedRunSeconds":3266,
“kwhSaved":60.342324672236224,
”periodStart":"2016-10-09T06:00:00Z",
“savedMoney":1.5085581168059057,
“normalMoneyCost”:1.6226692279170167,
“periodName":"Sunday"
},
{
“maxTemperature":74,
“acRunSeconds":6822
,”savedRunSeconds":5657,
“kwhSaved":76.18189032209128,
“periodStart":"2016-10-10T06:00:00Z",
“savedMoney":1.904547258052282,
“normalMoneyCost":1.951922258052282,
“periodName":"Monday"
},
{
“maxTemperature":62,
“acRunSeconds":9311,
“savedRunSeconds":12,
“kwhSaved":28.03764418071857
,”periodStart”:"2016-10-11T06:00:00Z",
“savedMoney":0.7009411045179643,
“normalMoneyCost”:0.7656008267401866,
“periodName":"Tuesday"
},
{
“maxTemperature":78,
“acRunSeconds":11275,
“savedRunSeconds":1431,
“kwhSaved":34.191927009102564,
“periodStart":"2016-10-12T06:00:00Z",
“savedMoney":0.8547981752275642,
“normalMoneyCost":0.9330967863386753,
“periodName":"Wednesday"
},
{
“maxTemperature":78,
“acRunSeconds":17967,
“savedRunSeconds":11864,
“kwhSaved":26.880751977008043,
“periodStart":"2016-10-13T06:00:00Z",
“savedMoney":0.6720187994252012
,”normalMoneyCost”:0.7967896327585345,
“periodName":"Thursday"
},
{
“maxTemperature":78,
“acRunSeconds":7649,
“savedRunSeconds”:2008,
“kwhSaved":4.5674527454968805,
“periodStart":"2016-10-14T06:00:00Z",
“savedMoney":0.11418631863742201,
“normalMoneyCost":0.16730437419297756,
“periodName”:"Friday"
},
{
"maxTemperature":73,
“acRunSeconds":6174,
“savedRunSeconds":1876,
“kwhSaved":5.251414465658444,
“periodStart":"2016-10-15T06:00:00Z",
“savedMoney":0.1312853616414611,
“normalMoneyCost”:0.1741603616414611,
“periodName":"Saturday"
}
],
“temperatureUnit":"F",
“currency":
{
“name":"USD",
“symbol":"$"
}
}

How can I extract specific values from this array? For example, if I wanted to retrieve the value "1.5085581168059057" under the "savedMoney" heading and assign it to a variable like this:

var savings_graph1 = 1.5085581168059057

What would be the best approach to achieve this? It seems like looping through the array might be necessary, but my attempts so far have resulted in errors such as "undefined" or [object Object].

The ultimate objective is to present this number on a graph for visual representation of the savings; however, I'm struggling to correctly fetch the desired value from the array into a variable that can be utilized within my JavaScript code.

This extracted number from the array will be assigned to the .data() field in the following D3.js code snippet that generates the graph:

vizs[0]
    .data(280)                              // current value
    .min(0)                                 // min value
    .max(100)                               // max value
    .capRadius(1)                           // Sets the curvature of the ends of the arc.
    .startAngle(250)                        // Angle where progress bar starts
    .endAngle(110)                          // Angle where the progress bar stops
    .arcThickness(.12)                      // The thickness of the arc (ratio of radius)
    .label(function (d,i) {                 // The 'label' property allows us to use a dynamic function for labeling.
        return d3.format("$,.2f")(d);
    });

vizs[1]
    .data(550)                              // current value
    .min(0)                                 // min value
    .max(200)                               // max value
    .capRadius(1)                           // Sets the curvature of the ends of the arc.
    .startAngle(210)
    .endAngle(150)
    .arcThickness(.07)
    .label(function (d,i) { return d3.format(".0f")(d); });

vizs[2]
    .data(820)                              // current value
    .min(0)                                 // min value
    .max(300)                               // max value
    .capRadius(1)                           // Sets the curvature of the ends of the arc.
    .startAngle(180)
    .endAngle(180)
    .arcThickness(.04)
    .label(function (d,i) { return d3.format(".0f")(d) + "%"; });

In summary, the process involves completing an AJAX GET request, extracting relevant data from the array to a variable, using this variable in the D3 code, and plotting the data on a graph for user visualization. Any insights on effectively fetching the data from the array to a JavaScript variable are highly appreciated.

The structure of the AJAX request is outlined below:

function getSavings() {

    var baseUrl = $('#stage_select').find(":selected").val();

    $('#date-output').html("UTC date now: " + moment.utc().format());

    var url = baseUrl + "/savings/acunits/{acid}/random";

    var username = document.getElementById('email').value;
    var password = document.getElementById('password').value;
    var data = {"email" : username , "password" : password};
    $('#output').append("request " + url + "\n");
    $.ajax({
        type: "GET",
        url: url,
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(data),
        processData: false,
        async: true,
        beforeSend: function (xhr) {
        xhr.setRequestHeader ('Authorization', 'Basic ' + btoa(username + ':' + password));
        },
        success: function (res) {
            $('#output').append("response -> " + JSON.stringify(res) + "\n\n");
        },
        error: function (jqxhr) {
            $('#output').append("response " + JSON.stringify(jqxhr.responseText) + "\n\n");
        },
    });
}

Answer №1

Finally cracked it!

The array needed to be evaluated like this:

var all =  eval("(function(){return " + array + ";})()");

Once that step was completed,

alert(all.savings[0].savedMoney);
functioned perfectly.

Big thanks to Jaco for the most helpful answer.

Here is the full AJAX call code snippet:

$.ajax({
    type: "GET",
    url: url,
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(data),
    processData: false,
    async: true,
    beforeSend: function (xhr) {
        xhr.setRequestHeader ('Authorization', 'Basic ' + btoa(username + ':' + password));
    },
    success: function (res) {
        $('#output').append(JSON.stringify(res));
        var firstDivContent = document.getElementById('output');
        var array = firstDivContent.innerHTML;
        var all =  eval("(function(){return " + array + ";})()");
        alert(all.savings[0].savedMoney);

    },
    error: function (jqxhr) {
        $('#output').append("response " + JSON.stringify(jqxhr.responseText) + "\n\n");
    },
});

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

"What could be the reason for the malfunctioning of this php/ajax code

I am currently facing an issue with a live search functionality on my website. The search is working fine for two out of the three radio buttons - "Professor" and "Department". However, the code related to the "Course" radio button doesn't seem to be ...

Java hashmap can use an array as a key

I've implemented a method that retrieves data from an Excel file and stores it in a HashMap, using an array as the key. public HashMap<List<String>, List<String[]>> sbsBusServiceDataGnr() throws IOException { System.out.pri ...

Changing a dictionary into a pandas DataFrame

Here is the format of my data: {u'"57e01311817bc367c030b390"': u'{"ad_since": 2016, "indoor_swimming_pool": "No", "seaside": "No", "handicapped_access": "Yes"}', u'"57e01311817bc367c030b3a8"': u'{"ad_since": 2012, "indoo ...

Append odd numbers twice and even numbers once using list comprehension

Currently diving into the world of list comprehensions and faced with a unique challenge that has left me searching for answers. The task at hand is as follows: How can we manipulate an array [1,2,3,8,9] to return each odd number duplicated, while only re ...

Navigating the maze of Express.js routes

When attempting to use sendFile to call my index.html page, I encountered a problem. The issue is that the index.html page displays without any of the CSS or JS/jQuery effects applied. This is what my server.js file looks like: var express = require("exp ...

JavaScript's toFixed method for decimals

I am encountering an issue with displaying prices for my products. I have labels in the form of "span" elements with prices such as 0.9, 1.23, and 9.0. I am using the method "toFixed(2)" to round these prices to two decimal places. However, I have notice ...

Converting authentication from Python to JavaScript, securing your JS application

Could someone assist me with translating this snippet of python into javascript? auth = "Basic " + base64.b64encode(bytes(IdentityClientId + ":" + IdentityClientSecret, "utf-8")).decode('ascii') My attempted solution: var auth = "Basic " + une ...

Ways to retrieve index values from Elasticsearch using Python

I transferred 3 JSON objects from an array to a local Elasticsearch index named "amazon" via localhost. Upon checking the index on localhost, the following output is displayed: {"amazon":{"aliases":{},"mappings":{"product-title":{"properties":{"images":{ ...

Understanding the concept of "this" within a callback situation

Given class functions game.PlayScreen = me.ScreenObject.extend({ onResetEvent: function() { this.setAll(); //calls setAll(), which calls setGlobals() this.saveNextLevelData(this.setAll); }, saveNextLevelData : function (cal ...

The decrementing of jQuery.ajax.active or jQuery.active is not working in Chrome

Despite my extensive research, I have yet to find a solution to my dilemma. Here's the issue: I have a form with three input fields that trigger separate AJAX calls on blur events. These AJAX calls check for the existence of the input data. Upon form ...

Establish a JSONB index in Postgres for a sub-object within an array

My table myTable includes a JSONB column called myJsonb with a specific data structure that I wish to index, shown below: { "myArray": [ { "subItem": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

modern marquee

I have implemented a marquee tag that displays news from my database. In order to keep the marquee up-to-date without refreshing the entire page, I utilized ajax (update_panel + timer). However, I am encountering an issue where the marquee does not continu ...

Tips for getting a sticky table header and including a limited number of columns, each with checkboxes or input fields

Encountering issues while trying to implement functionality with a jQuery library. One specific problem is the inability to interact with checkboxes on sticky columns, as well as difficulties clicking and typing in text fields. I am utilizing the jQuery S ...

The JavaScript indexOf method in an unordered list incorrectly returns the index of a specific event

Looking to retrieve the index number of an 'li' element within a 'ul' from the HTML structure. I attempted to convert the 'ul' into a list and access its children using: [...ul.children] However, upon targeting any of the chi ...

What could be the reason for jQuery AJAX sending requests repeatedly?

I have a message board where users can comment on messages similar to Facebook. When you click the "comment" link, a textarea slides down for you to write your comment. However, if you click "comment," then cancel so the textarea slides back up, and then c ...

Initiating an AJAX call with custom headers

According to David Flanagan's book "JavaScript: The Definitive Guide, 5th Edition", it is recommended to send request headers before making an AJAX request. Is it necessary to do this for compatibility across different browsers? request.setRequestHe ...

Struggling to get CORS request to function properly

I am encountering a CORS issue while trying to retrieve data from a webservice on a different domain. Within my controller, I have the following code: $http({method: 'GET', url : 'http://somewebserviceapi.com?idAppli=' + appId, header ...

Developing several sliders and ensuring they operate independently of each other

I am currently in the process of developing multiple sliders for a website that I am building. As I reach the halfway point, I have encountered a problem that has stumped me. With several sliders involved, I have successfully obtained the length or count ...

Navigate to a specific hidden div that is initially invisible

Currently, I am working on a web chat application using next.js. The app includes an emoji picker button, which, when clicked, displays a menu of emojis. However, the issue I am facing is that the user has to scroll down in order to see the emoji menu. I a ...

Using ES6, one can filter an array of objects based on another array of values

Seeking assistance with creating a function to filter an array of objects using another array as reference values. For example: The array containing objects: const persons = [ { personId: 1, name: 'Patrick', lastName: 'Smit ...