Stack survey data loops

Updated at September 13th, 2022

Programmatically stack survey data loops (e.g. patient cases) by adding the code below as a project data process.

Data process code

The example code below selectively stacks looped data. Modify the stacked_elements to specify the looped data columns (minus the suffice that represents the loop) in the survey. Also adjust the conditional statements and weights in the code. 

var rows = data["main"]   //Define rows
var stacked = [];         //Define stacked as an empty array
// Stack patient case data
// This first code block specifies questions looped across cases
var stacked_elements = [
rows.forEach(function (row) {    //Do something for each row
  for (var i = 1; i <= 5; i++) { //Define the condition for the loop to run                                        //The variable is set to “1”, every time the loop runs                          //it's incremented by one (i++), loop continues until i <= 5
      row.CaseNumber = i;
    var new_row = _.clone(row);  //Clone rows to create new rows = i;
    new_row.md_weight = 0.2;     //Define MD level weight
    new_row.pt_weight = 1;       //Define Patient level weight
     stacked_elements.forEach(function(element) {  //Do something for each element       
  new_row[element.replace('Q','q')+".1"] = row[element+"_"+i]; //Replace Q with q                                                 //Add “.1” to end of each element

        delete new_row[element+"_1"];         //Delete elements with “_1”
        delete new_row[element+"_2"];
        delete new_row[element+"_3"];
        delete new_row[element+"_4"];
        delete new_row[element+"_5"];
        stacked.push(new_row);                //Push new rows into var stacked
rows = stacked;
return rows;                                                

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?