Reputation: 97
I have defined a JS array as below:
var forecastJSArray=new Array();
and then I am trying to add my json objects into this array using push, as below:
$.getJSON("api-detail.json")
.then(function (forecast){
$.each(forecast, function() {
self.forecastJSArray.push({
rank: this.rank,
rep: this.rep,
total: this.total,
});
});
})
;
But when I run this code, it gives me an error as: Cannot read property 'push' of undefined TypeError: Cannot read property 'push' of undefined
My final array should look like this:
[
{
"rank" : 1,
"rep" : "rep1",
"total" : 10,
}, {
//...etc
}
]
Would be really grateful if someone can give me an idea where I am going wrong with this. Thanks a lot in advance.
EDIT: The code is enclosed inside an oracle-jet view model (which uses knockoutjs view model), and this is something like this, with a RequireJS block:
define(['ojs/ojcore', 'knockout', 'jquery', 'ojs/ojselectcombobox',
'ojs/ojtable', 'ojs/ojbutton'], function(oj, ko, $) {
function DashboardViewModel() {
var self = this;
... earlier code
... earlier code
}
return new DashboardViewModel();
});
as $.getJSON returns asynchronously, I am finding it difficult to use the data outside the callback function. So trying to push the data into a JS array first. Please let me know if you need any additional information. TIA.
Upvotes: 0
Views: 2409
Reputation: 40842
var forecastJSArray
defines forecastJSArray
in the scope of a function or in the global scope.
self.forecastJSArray
would only work if self
refers to window
and forecastJSArray
is defined in the global scope. In general you should not define a variable in the global scope.
TypeError: Cannot read property 'push' of undefined
Tells you that self
is undefined
(not holding any value).
So if var forecastJSArray
defined in a reachable scope for the code in the $.each(forecast, function() {
callback, then you would write: forecastJSArray.push
without the self.
.
Upvotes: 1
Reputation: 50291
First, from your side it is not possible to understand whether you have defined self
anywhere.
Secondly, you have created an array forecastJSArray
You can try by removing the self & directly refer the array
forecastJSArray.push({
rank: this.rank,
rep: this.rep,
total: this.total,
});
Upvotes: 1