[英]How to access items in a JavaScript array?
I have an AJAX GET that returns an array that looks like the following: 我有一个AJAX GET,它返回的数组如下所示:
{
“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 do I grab individual values from the array? 如何从数组中获取单个值? For instance if I wanted to return the value “1.5085581168059057" for the "savedMoney" heading in the array and set it equal to the following variable:
例如,如果我想为数组中的“ savedMoney”标题返回值“ 1.5085581168059057”,并将其设置为等于以下变量:
var savings_graph1 = 1.5085581168059057
How would I do this? 我该怎么做? I assume I would have to loop through the array and find it but every time I try I get "undefined" or [object Object] errors.
我认为我必须遍历数组并找到它,但是每次尝试时,我都会遇到“未定义”或[对象对象]错误。
The end goal is to place that number into a graph and plot savings; 最终目标是将该数字放入图表中,并绘制出节省量的图表; I just can't seem to get the correct number from the array into a variable so I can use it in my JavaScript.
我似乎无法从数组中获取正确的数字到变量中,因此可以在JavaScript中使用它。
The number from the array will be placed into the .data() field in the following D3.js that will graph the number on a chart. 数组中的数字将放置在以下D3.js中的.data()字段中,该D3.js将在图表上绘制该数字。
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) + "%"; });
The end result will be as follows: AJAX GET request completed, data is taken from the array and sent to a variable, variable is used in the D3 code and data is then plotted on a graph for the end user. 最终结果如下:AJAX GET请求完成,从数组中获取数据并将其发送到变量,D3代码中使用变量,然后将数据绘制在图形上以供最终用户使用。 If anyone knows how to get the data from the array to a Javascript variable I would be greatly appreciative.
如果有人知道如何将数据从数组中获取到Javascript变量,我将不胜感激。
The AJAX request looks like the following: AJAX请求如下所示:
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");
},
});
}
Figured it out! 弄清楚了!
The array needed eval as follows: 该数组需要评估,如下所示:
var all = eval("(function(){return " + array + ";})()");
once that was done alert(all.savings[0].savedMoney);
一旦完成
alert(all.savings[0].savedMoney);
worked. 工作了。
Thanks Jaco, your answer was closest. 感谢Jaco,您的回答是最接近的。
The complete AJAX call looks like this: 完整的AJAX调用如下所示:
$.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");
},
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.