javascriptarraysjsonapiextract

API JSON javascript extract data loop array


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!


Solution

  • 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.