'How to use for each to create buttons and then add individual id's that pull from the properties of an object

I am creating a quiz and have gotten to the point that I can create the buttons that contain the 4 possible answers. Now I would like to take the property that each value is coming from and make it that buttons ID.

 Object.values(currentAnswers).forEach(value => {
    console.log(value);
    let btn = document.createElement('button');
    btn.innerHTML = value
    quizContainer.appendChild(btn)
    textContent = currentAnswers;
});

Here is an example of the object I am pulling the data from

const myQuestions = [
{
    question: "When using an addEventListener what is the proper syntax?",
    answers: {
        a: "variable.addEventListener('click', function())",
        b: "addEventListener{click} = function",
        c: "variable.addEventListener(click, function)",
        d: "variable.onclick ()"

    },
    correctAnswer: 'a',
},

I can get the buttons to generate but I am unable to assign them the proper ID's



Solution 1:[1]

Use Object.entries to not just get the values but also the keys:

Object.entries(currentAnswers).forEach([key, value] => {
    console.log(value);
    let btn = document.createElement('button');
    btn.innerHTML = value;
    btn.id = key;
    quizContainer.appendChild(btn);
    textContent = currentAnswers;
});

Solution 2:[2]

There's a lot going on in the example provided so I'll navigate through it briefly:

  • Static tags are form#quiz and ol.
  • Run only once to build entire quiz:
    • Each group is <li>, <p>, <fieldset>, and 4 <button>s:
    • paragraph
      // The prompt
      <p>obj.question</p>
      
    • fieldset
      // #qa1 is question 1, #qa2 is question 2, ...#qaN
      <fieldset id="${qa(index+1)}"></fieldset>
      
    • button
      // #a1 - #d1 are the answers for question 1, etc.
      <button id="${a-d}${index+1}" value="${a-d}">Text of answer</button>
      
    • An array of answers (answerKey) is returned.
      console.log(answerKey) // ['a', 'c', 'b']
      

const QA = [{
  question: "When using an event listener what is the proper syntax? (Assume 'x' is a DOM object and 'clickHandler' is a named function)",
  answers: {
    a: "x.addEventListener('click', function(){console.log('test')})",
    b: "addEventListener{click} = clickHandler",
    c: "x.addEventListener('click', clickHandler())",
    d: "x.onclick()"
  },
  correct: 'a'
}, {
  question: "What event property is used to refer to the element that an event is attached to?",
  answers: {
    a: "event.target",
    b: "event.data",
    c: "event.currentTarget",
    d: "event.horizon"
  },
  correct: 'c'
}, {
  question: "The use of which type of event handler is strongly NOT recommended.",
  answers: {
    a: "x.addEventListener('click', function(){ console.log('pick me!') })",
    b: "<button id='x' onclick='pick(this)'>Pick Me!</button>",
    c: "x.onclick = pick",
    d: "x.onclick()"
  },
  correct: 'b'
}];
const quiz = document.forms.quiz;
const list = document.querySelector('ol');

let answerKey = QA.map((obj, idx) => {
  const qa = `<li>
                <p>${obj.question}</p>
                <fieldset id='qa${idx+1}'></fieldset>
              </li>`;
  list.insertAdjacentHTML('beforeend', qa);
  let fSet = quiz.elements['qa' + (idx + 1)];

  Object.entries(obj.answers)
    .forEach(([key, val]) => {
      let btn = document.createElement('button');
      btn.value = key;
      btn.textContent = val;
      btn.id = key + (idx + 1);
      fSet.append(btn);
    });
    return obj.correct;
});

console.log(JSON.stringify("Answer Key: " + answerKey));
button {
  display: block;
  width: 100%;
  min-height: 2.4rem;
  text-align: left;
  cursor: pointer;
}


/* For demo purposes only */

.as-console-row::after {
  width: 0;
  font-size: 0;
}

.as-console-row-code {
  width: 100%;
  word-break: break-word;
}

.as-console-wrapper {
  max-height: 1.5rem !important;
  min-width: 100%;
}
<form id='quiz'>
  <ol></ol>
</form>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christian Fritz
Solution 2