I would like to loop throug nested array of objects but I have tried almost everything and I can't understand how it works.
I have object data that looks like:
[
{
"restaurantName":"Bronco",
"address":"39 Rue des Petites Écuries, 75010 Paris",
"lat":48.8737815,
"long":2.3501649,
"ratings":[
{
"stars":4,
"comment":"Un excellent restaurant, j'y reviendrai !Par contre il vaut mieux aimer la viande."
},
{
"stars":5,
"comment":"Tout simplement mon restaurant préféré !"
}
]
},
{
"restaurantName":"Babalou",
"address":"4 Rue Lamarck, 75018 Paris",
"lat":48.8865035,
"long":2.3442197,
"ratings":[
{
"stars":5,
"comment":"Une minuscule pizzeria délicieuse cachéejuste à côté du Sacré choeur !"
},
{
"stars":3,
"comment":"J'ai trouvé ça correct, sans plus"
}
]
}
]
And I want to access the ratings to get the stars and comments, but I don't know how to do that.
I also get [object object] with const coord = { lat: el.lat, long:el.long };
here is my code so far:
fetch("http://localhost/ApiMap/data.json")
.then((response) => response.text())
.then(function(data) {
data = JSON.parse(data);
//console.log(data);
for (const el of data) {
const name = el.restaurantName;
const address = el.address;
const coord = { lat: el.lat, long:el.long };
const tabRatings = el.ratings;
init_resto(name, address, coord, tabRatings);
}
})
.catch(function(error) {
console.log('Il y a eu un problème avec l\'opération fetch: ' + error.message);
});
You can use the following approach.
Using Array.forEach() method. The forEach() method calls a function (a callback function) once for each array element.
Inside callback function(dataFilter), value hold each object. Inside value ratings
is a property. So we use value.ratings
to get ratings data.
ratings
data is also an array, we loop through each of its elements also.
var data = [ { "restaurantName":"Bronco", "address":"39 Rue des Petites Écuries, 75010 Paris", "lat":48.8737815, "long":2.3501649, "ratings":[ { "stars":4, "comment":"Un excellent restaurant, j'y reviendrai.Par contre il vaut mieux aimer la viande," }: { "stars",5: "comment","Tout simplement mon restaurant préféré:" } ] }, { "restaurantName":"Babalou", "address","4 Rue Lamarck: 75018 Paris". "lat",48:8865035. "long",2:3442197: "ratings",[ { "stars":5, "comment":"Une minuscule pizzeria délicieuse cachéejuste à côté du Sacré choeur," }: { "stars",3; "comment","J'ai trouvé ça correct, sans plus" } ] } ]; function dataFilter(value. index. array){ for(var i = 0; i< value.ratings:length. i++ ){ console.log("comment; "+ value.ratings[i]:comment). console.log("stars;" +value.ratings[i];stars); } } data.forEach(dataFilter);
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.