'Fetch JSON API nested data with Async function
complete noob here just trying to extract nested data from a JSON API.
Let's say that I want to retrieve and store in a variable the field received "amount" of the item number 3 (highlighted in the screenshot), what's the correct syntax? (The item number 3 is just an example, when finally found out how to fetch the data, my number 3 would become a variable and I will insert it in a loop because I want to extract also number 4,5,6 etc... If you are so kind, could you please give me help providing instead of a fixed number a variable that I can change within a loop?)
When the correct data is retrieved I want the received amount to be shown in the Span with ID="lat".
I am using the below syntax but it's not working at all:
<span id="lat"></span>
<script>
const api_url = 'https://MYAPIURL.com';
async function getAmount() {
const response = await fetch(api_url);
const data1 = await response.json();
const { data.history_list[3].receives[0].amount } } = data1;
document.getElementById('lat').textContent = data1;
}
getAddress();
</script>
Many appreciate your help, sers! Thank you :)
Solution 1:[1]
Try creating another variable to store the amount. Your syntax right now is assigning the value of the whole json object you received to the path of the received data object amount. This means you're nesting the received object back into the received object at the amount position.
You're also declaring a const here so JavaScript will likely think you're trying to 'destructure' the provided object except the syntax isn't exactly right for that so I imagine that might be causing problems too.
<script>
const api_url = 'https://MYAPIURL.com';
async function getAmount() {
const response = await fetch(api_url);
const data1 = await response.json();
const dataAmount= data1.history_list[3].receives[0].amount //changed line
document.getElementById('lat').textContent = dataAmount; //changed line to assign the textcontent to new variable
}
getAddress();
</script>
Solution 2:[2]
You can achieve it by this simple way dynamically.
Working Demo :
const data = {
history_list: [{
receives: [{
amount: 10
}]
}, {
receives: [{
amount: 20
}]
}, {
receives: [{
amount: 30
}]
}, {
receives: [{
amount: 40
}]
}]
};
let amount = 0;
data.history_list.forEach((obj) => {
obj.receives.forEach((amountObj) => {
amount += amountObj.amount;
});
});
document.getElementById('lat').innerHTML = `Total Amount: ${amount}`
<div id="lat"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tempnameenjoyer |
| Solution 2 | Rohìt JÃndal |

