Is there a way to iterate through an api using an ajax "GET" method on a given url? I have a series of ranks with data contained therein and I'm trying to use a for loop to access the data. The api is structured as such:
{
"top_5":{
"rank_1": [
123,
456,
],
"rank_2": [
123,
456,
],
}
}
And my ajax call in the html is written like so:
<script>
for (let i = 1; i < 6; i ) {
$.ajax({
method: "GET",
url: '/refunds/api',
success: function(data){
metric = data.top_5.rank_1
myDiv = 'myChart' i
barChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
}
</script>
The loop works for generating a unique div id, but now I'm stuck trying to engineer the metric
variable so that is dynamic and iterates to data.top_5.rank_i 1
on each loop. I think I need to use the map function, but I'm not sure how'd I'd implement it. Any help would be appreciated.
CodePudding user response:
I believe
metric = data.top_5["rank_" i]
could work. It's called bracket notation, can be useful when you need to access dicts/objects with variable names.
metric = data["top_5"]["rank_" i]
would also work for example.
metric = data.top_5."rank_" i
doesn't work because the interpreter doesn't know what to do with that. For the dot notation it needs it to be typed out like
metric = data.top_5.rank_0
Additionally I noticed you are making 6 api calls where I belive you can make only 1 api call (should improve performance). This would be the modification for that:
<script>
$.ajax({
method: "GET",
url: '/refunds/api',
success: function(data){
for (let i = 1; i < 6; i ) {
metric = data.top_5["rank_" i];
myDiv = 'myChart' i;
barChart();
}
},
error: function(error_data){
console.log("error");
console.log(error_data);
}
});
</script>