0

I am tryig to create dynamic buttons which is dependent on an object:

var buttonsMenu = {
  "A":{
    A1: 97,
    A2: 85, 
    A3: 65,
    A4: 70,
    A5: 40
  },
  "B":{
    B1: 97,
    B2: 85, 
    B3: 65,
    B4: 70,
    B5: 40
  }
};

var categoryButton = "A";//or B

// create a button for each category
for(property in buttonsMenu.categoryButton){// is where I am having issues
  var newEl = document.createElement('button');
  newEl.innerText = property;
  newEl.setAttribute('data-name', property);
  buttons.appendChild(newEl);

This works if I use the string A or B in the loop:

 for(property in buttonsMenu.A)

I thought the same would work if I would put it into a variable, but is not the case.:

var categoryButton = "A";
for(property in buttonsMenu.categoryButton){

What I am doing wrong here? Thanks in advance!

1 Answers1

1

you should use buttonsMenu[categoryButton]

const buttonsMenu = {
  "A": {
    A1: 97,
    A2: 85,
    A3: 65,
    A4: 70,
    A5: 40
  },
  "B": {
    B1: 97,
    B2: 85,
    B3: 65,
    B4: 70,
    B5: 40
  }
};

let categoryButton = "A" //or B

// create a button for each category
for (let property in buttonsMenu[categoryButton]) {
  let newEl = document.createElement('button')
  newEl.innerText = property
  newEl.setAttribute('data-name', property)
  document.body.appendChild(newEl)
}
apple apple
  • 10,292
  • 2
  • 16
  • 36