Looping over array in GET request

889 views Asked by At

I'm trying to build a Zap in Zapier that will

  1. Perform at single GET request that will return a JSON object.
  2. Loop over a key in that object that contains an array.
  3. POST a value from each array element to another URL.

I initially tried doing this with native Zapier elements, but I'm not sure how to take an action on each array item. I read in the Zapier Code documentation:

Setting the output to an array of objects will run the subsequent steps multiple times — once for each object in the array.

So now I'm doing the GET request in a Code element:

fetch('https://domain.com/path', { headers: { 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxxxx'} })
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        if (typeof json.arrayElem == 'object') {
          callback(json.arrayElem);
        } else {
          callback([]);
        }
    }).catch(callback);

This code returns an error:

Bargle. We hit an error creating a run javascript. :-( Error: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

I think I'm close, though, because if I change callback(json.arrayElem); to callback(json); I get the same error but with a single [object Object] instead of multiple.

Anyone have any pointers? I'm not married to using the Code element, but perfectly happy to if it will do what I need it to.

1

There are 1 answers

0
Bryan Helmig On BEST ANSWER

You should be returning proper callback arguments - the first argument is an Error or null.

Bad:

callback(json.arrayElem);

Good:

callback(null, json.arrayElem);

Same case for callback([]) vs. callback(null, []).