0

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.

1
  • remove self.. Commented Mar 21, 2017 at 5:09

2 Answers 2

1

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,
});
Sign up to request clarification or add additional context in comments.

Comments

1

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 forecastJSArrayis 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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.