Search code examples
javascriptdat.gui

Dynamically adding Dat.gui elements from array of objects


I am trying to extend a dat.gui menu to support multiple datasets as they are added by the user.

The aim is to rebuild the gui when a new dataset is loaded. So in the snippet below, it should add a new slider for each object in the array data.

function buildGui() {
  var gui_data = []
  gui = new dat.GUI();

  // data is an array of objects
  for (var i = 0; i < data.length; i++) {
      // create gui folder for each dataset with name var1
      gui_data.push(gui.addFolder(data[i].var1))

      // add a slider linked to data[i].var2 <- already set as an integer
      gui_data[i].frameno = gui_data[i].add(this,data[i].var2).name('var2');

  }
}

The last line raises an error:

TypeError: Cannot read property '0' of undefined

I know that this is the wrong object to pass, but cannot figure out what I am doing wrong.


Solution

  • So, in the above data[i].var2 did not exist - I was trying to reference the variable without having created it. Given that data[i].frameNo exists, the version below works.

    function buildGui() {
      var gui_data = []
      gui = new dat.GUI();
    
      // data is an array of objects
      data.forEach(function(each,i) {
          // create gui folder for each dataset with name var1
          gui_data.push(gui.addFolder(data[i].var1))
    
          // add a slider linked to data[i].var2 <- already set as an integer
          gui_data[i].frameno = gui_data[i].add(each,'frameNo').name('var2');
    
      }
    }