简体   繁体   中英

How do I loop JSON response to get specific data in Javascript or GAS

I Have an JSON response from an external API. Problem is i only know how to log the response but not manipulate it. In this case, I need to get some information from the response and loop through the entire response to show the list of all the users. Here is my code so far. Its not a good one, but this what i could do with my minimal javascript skills.

 };

var response= UrlFetchApp.fetch(url, options)
var call= JSON.parse(response.getContentText());
var people=call.data;
  var user= {}

    user.ID = call.data[1].id;
    user.Email = call.data[1].email;
    user.Name= call.data[1].display_name;

Logger.log(user)

} 

Sample response:

"data": [
    {
        "id":00126,
        "first_name": "Test",
        "last_name": "Test",
        "archived": false,
        "display_name": "Test Test",
        "email": "test@test.com",
        "termination_date": null,
        "mobile_phone": null,
        "office_phone": null,
        "deleted_at": null,
        "deleted": false,

    },

"data": [
    {
        "id":00126,
        "first_name": "Test",
        "last_name": "Test",
        "archived": false,
        "display_name": "Test Test",
        "email": "test@test.com",
        "termination_date": null,
        "mobile_phone": null,
        "office_phone": null,
        "deleted_at": null,
        "deleted": false,

    },

You can use Array.prototype.map to iterate through data and return required information only from the object

 let data = [ { "id": 00126, "first_name": "Test", "last_name": "Test", "archived": false, "display_name": "Test Test", "email": "test@test.com", "termination_date": null, "mobile_phone": null, "office_phone": null, "deleted_at": null, "deleted": false, }] let res = data.map(({id, email, display_name}) => ({ID: id, Email: email, Name: display_name})); console.log(res)

If ES6 is not supported

var res = data.map(function(userData) {
        return {ID: userData.id, Email: userData.email, Name: userData.display_name}
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM