Modify many elements using data process loops

Updated at August 14th, 2020

Often times you might need to make the same type of change to many elements. In the example below, we would like to sum across 13 product types for S10v1 and S10v2

One method is to create each of the new elements individually. This leads to many lines of similar code, and it is more prone to mistakes. If you want to go back and make changes to the logic it can be a tedious process. 

var rows = data["main"]
rows.forEach(function(row) {
    row.S10v_sum_1 = (+row.S10v1_1) + (+row.S10v2_1)
    row.S10v_sum_2 = (+row.S10v1_2) + (+row.S10v2_2)
    row.S10v_sum_3 = (+row.S10v1_3) + (+row.S10v2_3)
    row.S10v_sum_4 = (+row.S10v1_4) + (+row.S10v2_4)
    row.S10v_sum_5 = (+row.S10v1_5) + (+row.S10v2_5)
    row.S10v_sum_6 = (+row.S10v1_6) + (+row.S10v2_6)
    row.S10v_sum_7 = (+row.S10v1_7) + (+row.S10v2_7)
    row.S10v_sum_8 = (+row.S10v1_8) + (+row.S10v2_8)
    row.S10v_sum_9 = (+row.S10v1_9) + (+row.S10v2_9)
    row.S10v_sum_10 = (+row.S10v1_10) + (+row.S10v2_10)
    row.S10v_sum_11 = (+row.S10v1_11) + (+row.S10v2_11)
    row.S10v_sum_12 = (+row.S10v1_12) + (+row.S10v2_12)
    row.S10v_sum_13 = (+row.S10v1_13) + (+row.S10v2_13)


return rows;

A more succinct way to perform the same action across many elements is to run a loop within the function. This is done using square bracket notation. Within the brackets is an array, which is a special variable that can contain more than one value. 

In the example below, the function iterates over each value within the array of [].forEach. You can use square bracket notation with "+i" or any other subscript. The function takes the array object, finds the key and loops over the entire array. 

var rows = data["main"]
rows.forEach(function(row) {
    // Function to create new elements that sum across product type for S10v1 and S10v2 
            row["S10v_sum_"+i] = (+row["S10v1_"+i]) + (+row["S10v2_"+i])

return rows;
Notice in the code we've put a "+" before each value we want to add. The + operator immediately before a variable will return the numeric representation of the variable. This will ensure a number will be evaluated as a number rather than as a string, and be added numerically (2+7=9) not alphabetically ("2" + "7" = "27").

Reminder: For data processes, "Save" and "Run" the process after you are done editing the code view. To use the result of the process as the primary data for the project, you will need to set it as "Primary".
Data processes are specific to each project, and your code may not look identical to our example.

Was this article helpful?