0

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?

JAJohn
  • 3
  • 3
  • What is the value of *time*? From the code you've posted, it should produce a reference error. – RobG Nov 03 '19 at 20:45
  • var time = new Date('11/02/2019 12:00'). It is a date, not a string. – JAJohn Nov 03 '19 at 21:38
  • Ah. You mean the counter. Sorry forgot to change that. – JAJohn Nov 03 '19 at 21:59
  • please provide sample of the data returned in the response (exact respond). The reason for it to work outside the loop looks to be related to the iteration over the array. – Searching Nov 03 '19 at 22:10
  • ```var sampleData = [{ "id": "dasdasdas, "timetocheckin": "2019-11-03T23:58:00Z", "distance": { "value": 931.068, "unit": "miles" }, "Roomtype": "1", "Hotel": "someHOTEL", }] ``` – JAJohn Nov 04 '19 at 00:00
  • do i have to explicitly wait for the first loop with Asynch? i do not know why this is happening. My only guess was that the ifs are run before the iteration of "for loop" had been finished. feeling lost – JAJohn Nov 04 '19 at 00:05
  • have you tried saving the mutated `data` on a new array instead of changing it directly? – justelouise Nov 04 '19 at 02:00
  • i used asynch/await for these two loops, still did not work. i will try to save the mutated data on a new array. i will see – JAJohn Nov 04 '19 at 09:03

0 Answers0