I am trying to take some data from equal length CSV strings and split into arrays, then sequentially loop through these arrays to post individual lines to JSON through Zapier.
Here is my current code - for ease of my understanding, I have input simplified CSV strings as the first 3 lines:
var inputDataworkorders = "a,b,c,d,e,f"
var inputDatalats = "g,h,i,j,k,l"
var inputDatalongs = "m,n,o,p,q,r"
var workorder = inputDataworkorders.split(',')
var lat = inputDatalats.split(',')
var long = inputDatalongs.split(',')
var otherUrl = 'https://webpage.com/catch/13579/'
for (var i = 0; i <= workorder.length; i++) {
var payload = {
workorder: [workorder[i]],
lat: [lat[i]],
long: [long[i]],
};
}
fetch(otherUrl, {
method: 'POST',
body: JSON.stringify(payload)
}, callback)
.then(res => res.json())
.then(json => {
callback(null, json);
console.log(json)
});
What I am wanting is something like this for the first loop:
{workorder: "b",
lat: "h",
long: "n"}
And this for the second loop, and so on:
{workorder: "a",
lat: "g",
long: "m"}
I have read every possible help article I could find on this and have also tried to get some help via Freelancer, but to no avail. It doesn't seem like an advanced concept to me, but this is beyond my basic understanding. Any guidance is greatly appreciated.
Three issues:
payload
created in the loop. Otherwise payload
that you send with fetch()
will only be the very last object created in the for()
loop[]
wrapping the values for each property in the object<=
since length is a count that starts at 1 but array indexing starts at zero. If you do <=
the last iteration over shoots the length of the array var inputDataworkorders = "a,b,c,d,e,f"
var inputDatalats = "g,h,i,j,k,l"
var inputDatalongs = "m,n,o,p,q,r"
var workorder = inputDataworkorders.split(',')
console.log(workorder)
var lat = inputDatalats.split(',')
var long = inputDatalongs.split(',')
var otherUrl = 'https://webpage.com/catch/13579/'
// array to store all `payload` objects
var results =[];
for (var i = 0; i < workorder.length; i++) {
var payload = {
workorder: workorder[i],
lat: lat[i],
long: long[i],
};
results.push(payload)
}
console.log(results)
// now send `results` array to server