I was working on a project where I am required to go through an array of objects after fetching the data, manipulate them and then save those that fulfill certain conditions. Everything else was working, but the storing of the date in the object.
So basically, the code is like this (dateAdd taken from https://stackoverflow.com/a/1214753/12316962):
var baddata = []
fetch(fetch_url)
.then((response) => {
if (response.ok) {
response.json()
.then(data => data = data.workOpportunities)
.then(() => {
for (let i = 0; i < data.length; i++) {
data[i]['rooms'] = 0
data[i]['ontime'] = 0
data[i]['ontime'] = dateAdd(
new Date(time),
'second',
Math.round(data[i].distance.value / 50 * 60 * 60)
)
}
for (let i = 0; i < data.length; i++) {
if (/*checking ontime and other conditions*/) {
//do something
}
//do not do anything and push the data to baddata array
}
}
)
}
}).catch((err) => console.error(err))
data[i]['ontime']
is showing 'invalid date{}', and so the "if statements" are failing.
originally, I had only one loop for the whole thing, it was the same.
When I run the below, it works fine outside the loop.
data[0]['ontime'] = dateAdd(
new Date(time),
'second',
Math.round(data[0].distance.value / 50 * 60 * 60)
)
UPDATE: I populated the array with all objects I had gotten so far. It seems like the loop is running correctly if i run it as it is.
Does this have to do with an asynch function/fetch?
Where is the mess-up?