Reputation: 437
I have a code that is supposed to read a google sheet and push these into an array but i keep encountering an error that proData.push is not a function What could I be missing in this code?
function getData() {
var values = SpreadsheetApp.getActive().getSheetByName("Projects").getRange("A1:O").getValues();
values.shift();
var proData = [];
values.forEach(function(value) {
var proData = {};
proData.project_state = value[0];
proData.project_name= value[4];
proData.project_code= value[5];
proData.end_date= value[2];
proData.push(proData);
})
Logger.log(JSON.stringify(proData));
return proData;
}
I will appreciate help in looking at this.
Upvotes: 1
Views: 944
Reputation: 218827
This line tells the whole story:
proData.push(proData);
You're trying to push an object onto itself? Clearly this is an indication that something is wrong. So let's look at where you define proData
:
var proData = {};
That at least explains the error. proData
is an object, not an array. And an object indeed doesn't have a function called push
. You may have thought it was an array, because you defined an identically named array here:
var proData = [];
But for the line where you call .push
, how is the system to know which variable you intend for what purpose? In a higher scope you have an array named proData
, but in the current scope of this operation you obscured that with an object named proData
. And in doing so made the array inaccessible within the scope of the function passed to .forEach
.
To avoid confusing both the JavaScript engine and yourself in this matter, simply use different variable names. Re-naming the variable in the smaller scope has a lower impact, so that's a good candidate. (Though it's not always the best choice. If the variable in the higher scope is semantically not clear about what it contains then it should be re-named.)
Something like this:
values.forEach(function(value) {
var pd = {};
pd.project_state = value[0];
pd.project_name = value[4];
pd.project_code = value[5];
pd.end_date = value[2];
proData.push(pd);
});
Upvotes: 3