-4

I have an array of object and i want to loop through from this with the help of foreach but I got array I dont know why.
I want to display my array in a div.

This is my code:

var questions = [{
    question: 'my name is?',
    answere: ['jame', 'rock', 'batista', 'micheal'],
    correctAnswere: 'Ahmad'
  },
  {
    question: 'your name is?',
    answere: ['jhon', 'rock', 'watson', 'cook'],
    correctAnswere: 'Ahmad'
  }];
var getquiz = document.getElementById('demo')
questions.forEach(function(arrayitem) {
  getquiz = getquiz.innerHTML + arrayitem.question + "<br>";
});
<div id="getquiz">

</div>
Etheryte
  • 24,589
  • 11
  • 71
  • 116
Ahmad Bilal
  • 43
  • 1
  • 8

2 Answers2

0

This is because you are replacing getquiz dom element with a string instaed of concatatenate to innerHTML property. Also, your selector in getElementById is wrong.

Here is a correct snippet:

var questions=[{
    question:'my name is?',
    answere:['jame','rock','batista','micheal'],
    correctAnswere:'Ahmad'
  },
  {
    question:'your name is?',
    answere:['jhon','rock','watson','cook'],
    correctAnswere:'Ahmad'
  }
];

var getquiz=document.getElementById('getquiz');
questions.forEach(function (arrayitem)
{
  getquiz.innerHTML += arrayitem.question+"<br>";
});
<body>
    <div id="getquiz">

    </div>
</body>
ADreNaLiNe-DJ
  • 4,787
  • 3
  • 26
  • 35
0

Correction in your code is you are getting wrong document.getElementById('demo') instead of this you need to get document.getElementById('getquiz').

var questions = [{
    question: 'my name is?',
    answere: ['jame', 'rock', 'batista', 'micheal'],
    correctAnswere: 'Ahmad'
  },
  {
    question: 'your name is?',
    answere: ['jhon', 'rock', 'watson', 'cook'],
    correctAnswere: 'Ahmad'
  }
];

var getquiz = document.getElementById('getquiz')
questions.forEach(function(arrayitem) {
  getquiz.innerHTML += arrayitem.question + "<br>";
});
<div id="getquiz">

</div>

You can also use map method of array.

const questions = [{
  question: 'my name is?',
  answere: ['jame', 'rock', 'batista', 'micheal'],
  correctAnswere: 'Ahmad'
}, {
  question: 'your name is?',
  answere: ['jhon', 'rock', 'watson', 'cook'],
  correctAnswere: 'Ahmad'
}];

let getquiz = questions.map(item => {
  return item.question;
});

document.getElementById('getquiz').innerHTML = getquiz.join('<br>');
<div id="getquiz">

</div>
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44