0

I am calling from an API to get the response in json format. I would like to loop through that response and only get the data once as it brings up results twice.

var url = "api call";

var xhr = new XMLHttpRequest();
xhr.open("GET", url);

xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Authorization", "Bearer $token");

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
   }};

 
xhr.send();

Response in json I get is:

{
    "next": "url",
    "data": [
        {
            "profile_id": "00000000-0000-0000-0000-000000012f44",
            "value": {
                "signal": 0.61,
                "connection": "radio_low_power",
                "profile_id": "00000000-0000-0000-0000-000000013ee4"
            },
            "timestamp": "2022-07-22T14:52:37.359000Z",
            "type": "seen_device"
        },
        {
            "profile_id": "00000000-0000-0000-0000-000000012f44",
            "value": 0.61,
            "timestamp": "2022-07-22T14:52:37.359000Z",
            "type": "connection_signal"
        },
        {
            "profile_id": "00000000-0000-0000-0000-000000012f44",
            "value": {
                "signal": 0.58,
                "connection": "radio_low_power",
                "profile_id": "00000000-0000-0000-0000-000000013ee4"
            },
            "timestamp": "2022-07-22T14:37:32.096000Z",
            "type": "seen_device"
        },
...]}

I would like to loop and show only the type:"seen_device", value, timestamp.

This is what i've tried so far to loop the data:

for(let i = 0; i < xhr.length; i++) {
          let obj = xhr.responseText[i];
           console.log("hello");
          console.log(xhr.responseText.data);
      }
   }};
CSanchez
  • 11
  • 1

1 Answers1

-1

Because you looping async data, means you are trying to loop when data is not present, you need to add check if the response is not undefined and data on which you want to loop should have length

putting a sample code

function loopOverDat(){
 response && response.length && response.forEach(item => .....);
}
Raam Meena
  • 29
  • 9
  • _"Because you looping async data, means you are trying to loop when data is not present..."_ - There's no loop in OPs question. And most importantly: _"...I don't seem to be getting the response at all"_ – Andreas Jul 22 '22 at 16:40
  • Sorry let me apologise i get the response in json always from the api but what i meant is that when i try to loop the data and get the response from the loop data i am not getting it. – CSanchez Jul 25 '22 at 08:24