简体   繁体   中英

How can I put elements of an array inside object which is inside an array in separate divs?

I want to put the elements of an array in separate divs dynamically. The array is inside an object which is inside an array. I want to display each value of options property in separate divs. How can I achieve that through javascript? Thanks for your great help.

 var antonyms = [

 {
   question: "soft",
   options: ["dark", "white", "heavy", "hard", "down", "pretty", 
   "butter", "cotton"],
   answer: "hard"

  } ]


var x = "";

var i = 0;

function elements() {

if (i < antonyms.length) {

x += '<div class=option>' + antonyms[i].options.join(" ") + '</div>';

document.getElementById('container').innerHTML = x;

 i++;

    }

    x = "";

   }

elements();

Instead of calling join() to mash all of the array elements together in a string, you can use a loop to create a <div> element for each array element. I suggest that you look at the map() function for an array.

I hope next code helps you, Basically I'm assuming you have an outer array with question objects and for each one, you need to generate an HTML structure. So, I will define a method that takes one question object and generate the related HTML structure, then you can call that method for each question or for specifics ones.

 var antonyms = [ { question: "soft", options: ["dark", "white", "heavy", "hard", "down", "pretty", "butter", "cotton"], answer: "hard" }, { question: "test", options: ["one", "two"], answer: "two" } ]; // Define a method that generate the HTML for one question. function getQuestionHtml(q) { let qHtml = "<h2>" + q.question + " options:</h2>"; qHtml += q.options.map(o => '<div class="option">' + o + '</div>').join(""); return qHtml; } // Start showing the first question. Click event will show next question. let container = document.getElementById("container"); let button = document.getElementById("btnNext"); let qIdx = 0; container.innerHTML = getQuestionHtml(antonyms[qIdx]); button.addEventListener("click", function() { qIdx += 1; if (qIdx < antonyms.length) container.innerHTML = getQuestionHtml(antonyms[qIdx]); else button.disabled = true; }); 
 .option { border: 1px solid gray; background-color: skyblue; } 
 <div id="container"> </div> <br> <button id="btnNext" type="button">Next</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM