0

I want to fill a list with elements from a database. The data comes from a PHP file in JSON format. The JSON looks like this:

{"Venues" : [{"name":"McManus Galleries","id":"1"},{"name":"Dundee Law","id":"2"},{"name":"University of Abertay","id":"3"},{"name":"Baxter Park","id":"4"},{"name":"Overgate Shopping Centre","id":"5"}]}

Now I am handling this text with the following code:

obj = JSON.parse(this.responseText);

document.getElementById("list").innerHTML = "<a onclick='getVenue("+obj.Venues[0].id + ")'>" + obj.Venues[0].name + "</a><br>";
document.getElementById("list").innerHTML += "<a onclick='getVenue("+obj.Venues[1].id + ")'>" + obj.Venues[1].name + "</a><br>";

...and it works, but now I want to do it with a for-loop so no matter how many items "Venues" contains it is showing them all in the list. I got this code right now:

for(i = 0; i < obj.length; i++){
  document.getElementById("list").innerHTML += obj.Venues[i].name;
}

The problem here is, that obj.length returns 1. Does anybody know how to solve this?

3
  • 4
    obj.Venues.length. Commented Mar 30, 2017 at 13:01
  • You're iterating obj.Venues, not obj. Commented Mar 30, 2017 at 13:02
  • Worked, thanks a lot! Commented Mar 30, 2017 at 13:03

1 Answer 1

2

obj is the main object that has child Venues (that is an array to be used for iteration as below)

for(i = 0; i < obj.Venues.length; i++){
  document.getElementById("list").innerHTML += obj.Venues[i].name;
}

Sign up to request clarification or add additional context in comments.

1 Comment

For some reasons it was not possible to accept the answer so early

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.