Reputation: 35
I am trying to create a loop that will select the 'Photos' from each element in the array. However, they have no index numbers so I can't use a traditional for loop, using the loop iteration to select the next object each time. I can't seem to find a method that allows the selector to change each time the loop occurs.
This is what I have:
function fetchHalls() {
halls = [];
fetch(`https://www.data.brisbane.qld.gov.au/data/dataset/d14761ac-9bd9-4712-aefd-4bace8ca7148/resource/d7a4821d-eb68-454a-9615-356e17fd805b/download/bcccommunityhalls.json`)
.then(resp => resp.json())
.then(data => {
halls = halls.concat(data);
console.log(halls[0].Halls[ 'Acacia Ridge Hall' ].Description[4].Photos);
});
}
I basically want to change 'Acacia Ridge Hall', to the next hall name in the array and do that for as many halls are in the array. Which I also tried but '.length' returned nothing.
Here is a snippet of what the structure looks like:
Upvotes: 3
Views: 811
Reputation: 160
Firstly, you can get rid of concat if you are sure that the data returned from the server is always in Pascal Case. I have assumed in the below code that it always returns the data in Pascal Case. You could use either one of two methods to loop through the objects returned from the server:
Sample Code:
var halls = [];
fetch(`https://www.data.brisbane.qld.gov.au/data/dataset/d14761ac-9bd9-4712-aefd-4bace8ca7148/resource/d7a4821d-eb68-454a-9615-356e17fd805b/download/bcccommunityhalls.json`)
.then(resp => resp.json())
.then(data => {
halls = data.Halls;
//1st method
for (let value of Object.values(halls)) {
// Here loop through the description to access photo elements
console.log('value', value.Description)
}
//2nd method
Object.keys(halls).map(function (element, index, array) {
console.log("element", element);
console.log("index", index);
console.log("array", array);
});
});
Upvotes: 1
Reputation: 1595
Here's my solution:
for(let hall of Object.keys(data.Halls)) {
// Here hall is the hallname, e.g, "Acacia Ridge Hall"
// and data.Halls[hall] // is the value
const urls = data.Halls[hall]?.Description[4]?.Photos;
if(urls) {
// whatever you want to do with the urls
}
}
Upvotes: 2