简体   繁体   中英

How do I access children data in JSON response using Javascript/GAS

I am trying to access children data from a Json response to use it in an if statement but i don't know-how. Anyone know how to do this?

Here is the screenshot of the response and I have circled the object I want to access. I want only the summation to happen if the approval has a value ie status needs to be pending or approved, otherwise, no calculation will happen.

在此处输入图片说明

Here is the code that I use but don't know how to access the approaval={data=[{status}] form the JSON so as to use it

function showTimeData() {

    var users = getUsers()
    var endpoint = 'users/';
    var time_array = [];

    for (var i = 0; i < users.length; i++) {

        var url = 'https://api.10000ft.com/api/v1/users/' + users[i].id + '/time_entries?fields=approvals' + '&from=' + from + '&to=' + to + '&auth=' + TKF_AUTH;
        var response = UrlFetchApp.fetch(url, options);
        var info = JSON.parse(response.getContentText());
        var content = info.data;
        var total_hours = 0;


        for (var j = 0; j < content.length; j++) {
            if (content.data.approvals.data.length > 0) {
                hoursTotal = 0;
            }
            total_hours += parseInt(content[j].hours);
        }


        Logger.log('User name: ' + users[i].display_name + ' ' + 'User id: ' + users[i].id + '  ' + 'total hours: ' + total_hours)
    }

First of all. You need to fix the error(mentioned in the chat in comments): Replace this

if (content.data.approvals.data.length > 0) {
  hoursTotal = 0;
}

with this

if (content[j].approvals.data.length > 0) {
  hoursTotal = 0;
}

Then what you need is:

content[0].approvals.data[0].status

or an array of status es:

content[0].approvals.data.map(el => el.status)

or an array of all status es:

content.map(el => el.approvals.data.map(it => it.status)).flat(1)

but last example will work only in fairly new browsers.

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