0

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 :)

API STRUCTURE

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you ser, but I get this error referred to the row "const dataAmount= data1.history_list[3].receives[0].amount": ERROR -> "Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '3') at getAddress (index.html:26:46)" It seems that it doesn't like the numbers [3] and [0]. I tried also with (3) and (0) and 3/0 but every time I have an error. :\
Hmm there's probably a better solution but that's likely happening because the dataAmount is executing before the promise is resolved to actually fetch the data. Try adding await in front of data1 and then also before assigning the document.textContent in the next line. This queues up the promises so that it doesn't execute before. Else the actual execution order will be -> dataAmount = ...; then it will fetch(api_url) so its trying to get the properties on a yet undefined object
Thanks ser, I am still having the same problem. Added "await" here const dataAmount = await data1.history_list[3].receives[0].amount; AND document.getElementById('lat').textContent = await dataAmount; But I am getting the very same error posted in my previous comment :(
Are you sure that you're fetch request is currently pulling back data? If you console.log it is the JSON object still showing up
0

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>

Comments

0

Answering the old question.

It doesn't matter if you have nested data or not while using await/aysnc. Check for typos. Here is the full example to use await and async to access nested object. I am using public api in this example.

<!DOCTYPE html>
<html>
<body>

<h1>Users</h1>
<ul id="users"></ul>

<script>

async function getUsersNestedData() {

  const url = "https://jsonplaceholder.typicode.com/users";
  const ul = document.getElementById('users');
  const list = document.createDocumentFragment();
  
  try {
    const response = await fetch(url).then((response) => {
      return response.json();
    })
    .then((data) => {
      let users = data;

      users.map(function(theUser) {
        let li = document.createElement('li');
        let name = document.createElement('h2');
        let email = document.createElement('span');
        let address = document.createElement('div');

        name.innerHTML = `Name: ${theUser.name}`;
        email.innerHTML = `Email: ${theUser.email}`;
        address.innerHTML = `Address: ${theUser.address.street}, ${theUser.address.suite}, 
                            ${theUser.address.city}, ${theUser.address.zipcode}`;
        li.appendChild(name);
        li.appendChild(email);
        li.appendChild(address);
        list.appendChild(li);
        
        ul.appendChild(list);
        
      });
    })
    .catch(function(error) {
      console.log(error);
    });
  } catch (error) {
    console.error(error.message);
  }
}

getUsersNestedData();

</script>
</body>
</html>

Comments

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.