-3

This is the simplified code I'm working with. Is there a better way to find the correct bool? I'm a beginner so I dont understand keyword "this" completely, but is there a way to connect button with a coresponding object maybe with "this" or something simmilar?

arr = [
 {
   name: "obj1",
   bool: false,
 },
   {
   name: "obj2",
   bool: false,
 }
];

function buildButtons() {
  for (var i = 0; i < arr.length; i++) {
    let button = document.createElement("button");
    button.innerHTML = arr[i].name;
    button.onclick = function() {
      // is there a better way to find the correct bool?
      for (i = 0; i < arr.length; i++) {
        if (this.innerHTML === arr[i].name) {
          arr[i].bool = true;
        }
      }
    };

  window.document.body.appendChild(button);
  }
}

buildButtons();

1 Answers1

0

Your best bet is to change the data structure to a more appropriate one. Rather than having to loop through an array to find the correct name, just use the names as keys in a single object, so you can look them up directly. Altered code follows:

obj = { obj1: false, obj2: false} 

function buildButtons() {
  for (let name in obj) {
     let button = document.createElement("button");
     button.innerHTML = name;
     button.onclick = function() {
       obj[name] = true;
     } 
    window.document.body.appendChild(button);
  }
}

buildButtons();

Note that I've used let rather than var for the loop variable - this is necessary (in your version too) for the event handler functions to "capture" the correct value of the loop variable. See here for a very thorough explanation of this.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34