【问题标题】:How do I implement data reduce in Google App Script (Javascript ES5)如何在 Google App Script (Javascript ES5) 中实现数据缩减
【发布时间】:2020-01-28 06:25:40
【问题描述】:

我喜欢在 GAS 中实现数据缩减方面获得帮助,以便我只能处理满足特定条件的数据。

本质上是这段代码:

const total = data.reduce((acc, el) => {
  const {hours, approvals: {data}} = el;
  if (data.length && data.filter(e => e.status === 'approved' || 'pending').length >= 5) {
    acc += hours;
  }
  return acc;
}, 0);

console.log(total);

在此实现:

        var url = 'https://api.10000ft.com/api/v1/users/' + users[i].id + '/time_entries?fields=approvals' + '&from=' + from + '&to=' + to + '&auth=' + TKF_AUTH + '&per_page=' + TKF_PGSZ;
        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[j].approvals.data.length > 0 && content[j].approvals.data[0].status != 'ignored') {

                total_hours += content[j].hours;

            }
        }

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

}

有人有想法吗?

【问题讨论】:

    标签: javascript api loops google-apps-script reduce


    【解决方案1】:
    • 您希望将以下脚本转换为可与 Google Apps 脚本一起使用的脚本。

      const total = data.reduce((acc, el) => {
        const {hours, approvals: {data}} = el;
        if (data.length && data.filter(e => e.status === 'approved' || 'pending').length >= 5) {
          acc += hours;
        }
        return acc;
      }, 0);
      
      console.log(total);
      
    • 您已经确认上述脚本适用于您使用 Javascript 的情况。

    如果我的理解是正确的,那么这个答案呢?请认为这只是几个可能的答案之一。

    修改脚本:

    const total = data.reduce(function(acc, el) {
      const {hours: hours, approvals: {data: data}} = el;
      if (data.length && data.filter(function(e) {return e.status === 'approved' || 'pending'}).length >= 5) {
        acc += hours;
      }
      return acc;
    }, 0);
    Logger.log(total)
    
    • 箭头功能无法使用。
    • 不能使用const {hours, approvals: {data}} = el; 的解构赋值。请修改为const {hours: hours, approvals: {data: data}} = el;

    参考资料:

    如果我误解了您的问题并且这不是您想要的方向,我深表歉意。到时候能不能提供你期望的样例输入输出?借此,我想确认一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-13
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多