Just
Just

Reputation: 437

How to loop through JSON response in Javascript to get specific data

I am learning how to make API requests using Javascript.

I have made a GET request and got the following data and I would like to loop through them to get only id, display_name and email. This are to be stored in arrays. How do I complete the javascript code?

"data": [
        {
            "id": 222226,
            "display_name": "jane Doe",
            "email": "[email protected]",
        },
        {
            "id": 1111226,
            "display_name": "james",
            "email": "[email protected]",
        },
    {
            "id": 11126,
            "display_name": "Travis Mc",
            "email": "[email protected]",
         },

Heres is my javascript code.

var options = {
        method: 'get',
        headers: {
            Authorization: 'Bearer ' + auth
        }
    };
    var response= UrlFetchApp.fetch(url, options);
    var data = JSON.parse(response.getContentText());

I am not sure I am doing this loop part right.

for (var i = 0; i < data.length; i++) {
    Logger.log(data[i].display_name);
}

enter image description here

Upvotes: 0

Views: 3089

Answers (1)

Cesar Perez
Cesar Perez

Reputation: 109

I am going to assume you are using the Fetch Api. If so this means you are creating a Promise. When working with promises you will have to chain a then function to establish how to proceed. Promise.then((value)=>{ /* do something */ }); Since you are working with JSON data you must first parse it before it can become manipulatable for javascript. If you read the Fetch Api it explains how it resolves your promise and returns a Response based on the HTTP Response.

This exampled is borrowed from the Devloper Mozilla Org Check out the usage section of the Fetch API

fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(myJson);
  });

This examples illustrates how the fetch function resolves the promise that returns a response which is parsed then returned again to another then function which will now have the parsed data ready to manipulate.

In your case the code will look something like this

var options = {
    method: 'get',
    headers: {
        Authorization: 'Bearer ' + auth
    }
};

var response = UrlFetchApp.fetch(url, options)
.then((r)=>{ return r.json(); }).then((data)=>{
  for (let i = 0; i < data.length; i++) {
    Logger.log(data[i].display_name);
  }
});

Upvotes: 1

Related Questions