Changing values ​in objects reflects the last change throughout the object. (Google AppScript)

Viewed 33

I'm making a list of requests to do simultaneously with the fetchall class, but when I put it in a repeat loop or map the object to concatenate the endpoint with the values, the last value ends up being stored in the entire object:

function getMethod(rangeData, request, url, terminate){
  var data = []
  var requestsList = []

  rangeData.map(function(item){
    request['url'] = url + item + terminate
    requestsList.push(request)
  })

  var response = UrlFetchApp.fetchAll(requestsList)
  
  for (var i in response){
    data.push(JSON.parse(response[i].getContentText()))
  }

  return data
}

I've done a test with a log and it really goes through all the ID's I need, but when it writes to the object it does it in all the items ['url'] of the object.

1 Answers

I believe what you want is this, provided its just a URL.

rangeData.forEach(function(item){
  requestsList.push(url + item + terminate)
})

If its an object then:

rangeData.forEach(function(item){
  let newRequest = JSON.parse(JSON.stringify(request));
  newRequest.url = url + item + terminate;
  requestsList.push(newRequest);
})

I realized you were using Array.map() which returns a new array. You should be using Array.forEach() instead.

Related