简体   繁体   中英

How do I implement data reduce in Google App Script (Javascript ES5)

I like to get in help in implementing data reduction in GAS so that I can only process data that meet a certain condition.

In essence this code:

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);

Implemented in this:

        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)
    }

}

Anyone with an idea?

  • You want to convert the following script to the script which can be used with Google Apps Script.

     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);
  • You have already confirmed that the above script worked for your situation with Javascript.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modified script:

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)
  • The arrow function cannot be used.
  • The destructuring assignment of const {hours, approvals: {data}} = el; cannot be used. Please modify to const {hours: hours, approvals: {data: data}} = el; .

References:

If I misunderstood your question and this was not the direction you want, I apologize. At that time, can you provide the sample input and output you expect? By this, I would like to confirm it.

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