Reputation: 11030
I have the following code.
const timeLabels = [
{ name: "1:00 AM", present: true, label: ["1:00", "2:00"], value: "1:00" },
{ name: "2:00 AM", present: true, label: ["2:00", "3:00"], value: "2:00"},
{ name: "3:00 AM", present: true, label: ["3:00", "4:00"], value: "3:00" },
];
const targetedTimes = [["0:00", "1:00"], ["1:00", "2:00"]]
let actualTime = [];
console.log("getting time");
console.log("start: the actualTime is", actualTime);
for (var j = 0; j < timeLabels.length; j++) {
console.log("x");
var currItem = timeLabels[j];
var label = JSON.stringify(currItem.label);
var adTime = JSON.stringify(targetedTimes);
if (adTime.indexOf(label) >= 0) {
currItem.present = true;
} else {
currItem.present = false;
}
console.log("the current item is", currItem);
actualTime.push(currItem);
console.log("The actual time is", actualTime);
}
On the FIRST iteration, the currItem is
{name: "1:00 AM", present: true, label: Array(2), value: "1:00"}
But the actualTime is
[{name: "1:00 AM", present: true, label: Array(2), value: "1:00"},
{name: "2:00 AM", present: false, label: Array(2), value: "2:00"},
{name: "3:00 AM", present: false, label: Array(2), value: "3:00"}]
Why would the actualTime list have three values when I only append 1 on the first iteration?
Upvotes: 0
Views: 172
Reputation: 369
What is happening is that the console is printing a reference to the object (becuase arrays are a type of object in javascript), so by the time you print it and read it in the console, each console.log statement is pointing at the same final array, which is why the values is the same each time.
Have a look at this similar StackOverflow question for more insight.
I tried running your script on node and it printed out the array correctly on each iteration, with only one item in the first iteration, so your code is fine.
Upvotes: 1