skip to Main Content

I’ve succeeded at connecting and getting JSON data from API using this method:

<script type="text/javascript"> 
   fetch('https://api.web_address.com/vi/locations/10', {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer my_bearer_token'
    },
})
.then(response => {
    if (response.ok) {
      return response.json()

    } else {
      return Promise.reject({
        status: response.status,
        statusText: response.statusText
      })
    }
  })
.then(data => console.log('data is', data))
.catch(error => {
    if (error.status === 404) {
      // do something about 404
    }
  })
</script>

The API gives this data:

{
    "message": "OK",
    "data": {
        "id": 10,
        "name": "First floor",
        "count": 96,
        "percentage": 0.06,
        "timestamp": "2023-02-25T03:53:25.279Z",
        "isActive": true,
        "childCounts": [
            {
                "id": 11,
                "name": "Room 101",
                "count": 36,
                "percentage": 0.1,
                "isActive": true
            },
            {
                "id": 12,
                "name": "Room 102",
                "count": 17,
                "percentage": 0.06,
                "isActive": true
            },
            {
                "id": 13,
                "name": "Room 103",
                "count": 12,
                "percentage": 0.04,
                "isActive": true
            }
        ]
    }
}

How do I loop to get the "name" and "percentage"? And where do I put the loop?
Hope the description is clear to you because I’ve tried and tried and can’t get anything working…Please help!

4

Answers


  1. Loop over .data.childCounts.

    let o = { "message": "OK", "data": { "id": 10, "name": "First floor", "count": 96, "percentage": 0.06, "timestamp": "2023-02-25T03:53:25.279Z", "isActive": true, "childCounts": [ { "id": 11, "name": "Room 101", "count": 36, "percentage": 0.1, "isActive": true }, { "id": 12, "name": "Room 102", "count": 17, "percentage": 0.06, "isActive": true }, { "id": 13, "name": "Room 103", "count": 12, "percentage": 0.04, "isActive": true } ] } };
    for (const {name, percentage} of o.data.childCounts) {
      console.log(name, percentage);
    }
    Login or Signup to reply.
  2. My Answer:

    let o = { "message": "OK", "data": { "id": 10, "name": "First floor", "count": 96, "percentage": 0.06, "timestamp": "2023-02-25T03:53:25.279Z", "isActive": true, "childCounts": [ { "id": 11, "name": "Room 101", "count": 36, "percentage": 0.1, "isActive": true }, { "id": 12, "name": "Room 102", "count": 17, "percentage": 0.06, "isActive": true }, { "id": 13, "name": "Room 103", "count": 12, "percentage": 0.04, "isActive": true } ] } };
    
    o.data.childCounts.map((ele)=> {
      const {name, percentage} = ele;
      console.log(name, percentage)
    })
    

    Hope it would be help to you.

    Login or Signup to reply.
  3. My answer:

    <script type="text/javascript"> 
       fetch('https://api.web_address.com/vi/locations/10', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer my_bearer_token'
        },
    })
    .then(response => {
        if (response.ok) {
          return response.json()
    
        } else {
          return Promise.reject({
            status: response.status,
            statusText: response.statusText
          })
        }
      })
    .then(rawData => { // Add another 'then' block here
        const {data: {childCounts = []} = {}} = rawData; //default values when destructuring
        return childCounts.map(({name = '', count = 0}) => ({ // always good to have defaults
            name,
            count
        }))
    })
    .then(data => console.log('data is', data)) // Now this data is the data you want
    .catch(error => {
        if (error.status === 404) {
          // do something about 404
        }
      })
    </script>
    

    Note: Try and use async/await if you are dealing with promises.

    Login or Signup to reply.
  4. You can use map method with object destructuring syntax :

    const data = {"message":"OK","data":{"id":10,"name":"First floor","count":96,"percentage":0.06,"timestamp":"2023-02-25T03:53:25.279Z","isActive":true,"childCounts":[{"id":11,"name":"Room 101","count":36,"percentage":0.1,"isActive":true},{"id":12,"name":"Room 102","count":17,"percentage":0.06,"isActive":true},{"id":13,"name":"Room 103","count":12,"percentage":0.04,"isActive":true}]}};
    
    const processData = (data) => {
      const { childCounts } = data.data || {};
      return childCounts ? childCounts.map(({ name, percentage }) => ({ name, percentage })) : [];
    a;
    }
    
    console.log(processData(data));
    console.log(processData({})); // []
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search