0

I'm doing a quiz with only jquery and I need to get data from the JSON API through ajax, the data from the JSON API is randomly selected how do I get access properties of the objects?

I did it in this way but is there any other way I can do it instead of writing every single question down.

I'm new to Jquery:) please help

    $("p:eq(0)").text(data.results[0].question);
    $("p:eq(1)").text(data.results[1].question);
    $("p:eq(2)").text(data.results[2].question);
    $("p:eq(3)").text(data.results[3].question);
    $("p:eq(4)").text(data.results[4].question);
    $("p:eq(5)").text(data.results[5].question);
Object object
  • 872
  • 6
  • 18
simbaa
  • 11

1 Answers1

0

You can use a for loop:

for (var i = 0; i < data.results.length; i++) {
    $("p:eq(" + i + ")").text(data.results[i].question);
}
Nick Tiberi
  • 1,132
  • 12
  • 20
  • what does the $("p:eq(" + i + ")") do ? i dont understand that part – simbaa May 31 '19 at 17:42
  • When `i == 0` in the loop, `$("p:eq(" + i + ")")` will evaluate to `$("p:eq(0)")`. When `i == 1`, it will evaluate to `$("p:eq(1)")`, etc. – Nick Tiberi May 31 '19 at 17:49