The tutorial is here: Tutorial: Writing Spreadsheet data using JavaScript Objects
The full code can be found at the end of the tutorial.
I don’t get the for loop in the first function, runExample()
for (var i = 0; i < data.length; ++i) {
var rowData = data[i];
if (!dataByDepartment[rowData.department]) {
dataByDepartment[rowData.department] = [];
departments.push(rowData.department);
}
dataByDepartment[rowData.department].push(rowData);
}
I don’t get what is going on inside the if-statement.
What do they mean by dataByDepartment[rowData.department]) ???
dataByDepartment is initially empty… Is this creating a property??
Can someone please explain what that whole loop is doing? Thank you very much!
PS: I am still quite new to Javascript… Coming from C programming I am always confused by the object and property creations…
In general terms the function of the loop is to populate the
dataByDepartmentobject with one property for each (distinct) department, where each property will reference an array of data applicable to that department. Each iteration of the loop first checks whether there is already a property for the current department and if not it creates it. If it does need to create a new property it also adds the department to thedepartmentsarray.Some background: the following statement creates an object with initially no properties:
To assign a property “key1” with the value “value1” to that object you would then say:
Note that if a property called “key1” already existed it would be overwritten. The square-bracket syntax allows you to use property key names that are variable. So you can say:
Which will create a property with a name equal to whatever
myKeyevaluates to (“key2” in this case), and the value “value2”.So getting back to the actual code you quote, the if statement:
is checking whether
dataByDepartmentalready has a property with a key name equal to whatever is inrowData.department. The syntax is a shortcut roughly equivalent toif (dataByDepartment[rowData.department] != undefined).The first statement in the
if:creates a new property with the key name of whatever is in
rowData.departmentand the value of a new empty array. At that point if the property already existed it would be overwritten by a new empty array, hence the if test.The second statement in the
ifadds the department name to thedepartmentsarray:Finally, after the
if, the array referenced bydataByDepartment[rowData.department]has a new element added to it: