简体   繁体   English

如何使用 Javascript/GAS 在 JSON 响应中访问子数据

[英]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.我试图从 Json 响应中访问儿童数据以在if语句中使用它,但我不知道如何。 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这是我使用的代码,但不知道如何从 JSON 访问approaval={data=[{status}]以使用它

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:status数组:

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

or an array of all status es:或所有status的数组:

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

but last example will work only in fairly new browsers.但最后一个例子只适用于相当新的浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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