0

This may turn out to be a stupid mistake on my part, but my JSON object array is behaving unexpectedly.

The JSON object insertDoc has startDate and endDate fields and i'm trying to create a new object for each day in between -

            var insertDocs = [];
            var finalDate = insertDoc.endDate;

                while (insertDoc.startDate <= finalDate) {
                    insertDoc.endDate =  insertDoc.startDate;
                    console.log('doc is ' + JSON.stringify(insertDoc));
                    insertDocs.push(insertDoc);
                    insertDoc.startDate = new Date(moment(insertDoc.startDate).add(1, 'days')); 
                }

            ...

            for (var i = 0; i < insertDocs.length; i++) {
                console.log(JSON.stringify(insertDocs[i]));
            }

Here's the browser output -

doc is {"description":"testtask","endDate":"2019-04-01T00:00:00.000Z","startDate":"2019-04-01T00:00:00.000Z","status":"OPEN"}
doc is {"description":"testtask","endDate":"2019-04-02T00:00:00.000Z","startDate":"2019-04-02T00:00:00.000Z","status":"OPEN"}
doc is {"description":"testtask","endDate":"2019-04-03T00:00:00.000Z","startDate":"2019-04-03T00:00:00.000Z","status":"OPEN"}
doc is {"description":"testtask","endDate":"2019-04-04T00:00:00.000Z","startDate":"2019-04-04T00:00:00.000Z","status":"OPEN"}
doc is {"description":"testtask","endDate":"2019-04-05T00:00:00.000Z","startDate":"2019-04-05T00:00:00.000Z","status":"OPEN"}

Output of stringify - same doc printed 5 times

{"description":"testtask","endDate":"2019-04-05T00:00:00.000Z","startDate":"2019-04-06T00:00:00.000Z","status":"OPEN"}

So it seems each object is different and correctly printed but the array just seems to be 5 of the same object. The date values are different too

Am i missing something here?

Jay
  • 1,392
  • 7
  • 17
  • 44
  • 1
    You're pushing `insertDoc` every time. You need to clone the object if you want separate objects. – CertainPerformance Jan 22 '19 at 04:09
  • 1
    `insertDocs.push(insertDoc); insertDoc.startDate = new Date(moment(insertDoc.startDate).add(1, 'days'));` here sequence is wrong assignment should come before pushing it. – Just code Jan 22 '19 at 04:14
  • Thanks guys, indeed this concept was unclear to me. I was able to use `insertDocs.push(Object.assign({}, insertDoc))` to get this working – Jay Jan 22 '19 at 04:36

0 Answers0