Why isn't my JavaScript object growing when I try to add new dates?

I’m having trouble with a JavaScript object. I’m looping through a big list of items and trying to add dates to my object. But it’s not working like I thought it would.

Here’s what I’m doing:

let myDates = {}

for (let i = 0; i < bigList.length; i++) {
  let currentDate = bigList[i].dateInfo

  myDates = {
    ...myDates,
    dateEntry: currentDate,
  }
  console.log(myDates)
}

I thought this would make my object bigger each time. Like first it would be { dateEntry: '2022-05-01' }, then { dateEntry: '2022-05-01', dateEntry: '2022-05-02' }, and so on.

But when I look at the console, I only see one date. It’s like the object isn’t growing at all.

What am I doing wrong? How can I make my object keep all the dates?

I ran into a similar issue when I was working on a project tracking product inventory dates. The problem is that you’re using the same key (‘dateEntry’) for every iteration, so it’s just overwriting the previous value each time.

Here’s a trick I found that worked well:

let myDates = {}

for (let i = 0; i < bigList.length; i++) {
  let currentDate = bigList[i].dateInfo
  myDates[currentDate] = myDates[currentDate] ? myDates[currentDate] + 1 : 1
}

This approach not only stores all unique dates but also counts how many times each date appears. It’s been super helpful for me in analyzing date patterns in large datasets.

Another benefit is that you can easily check if a date exists by doing if(myDates['2022-05-01']). Just remember to handle potential timezone issues if you’re dealing with dates from different regions.

I see where you’re going wrong. The issue is with how you’re adding new entries to your object. In your current code, you’re using the same key ‘dateEntry’ for each iteration, which means you’re overwriting the previous value each time.

To fix this, you need to use unique keys for each date. Here’s a way to do it:

let myDates = {}

for (let i = 0; i < bigList.length; i++) {
  let currentDate = bigList[i].dateInfo
  myDates[`date_${i}`] = currentDate
}

This will create unique keys like ‘date_0’, ‘date_1’, etc., for each date. Alternatively, if you want to use the dates themselves as keys:

let myDates = {}

for (let i = 0; i < bigList.length; i++) {
  let currentDate = bigList[i].dateInfo
  myDates[currentDate] = true
}

This way, your object will grow with each iteration, storing all the dates as you intended.

hey man, i think ur problem is with the keys. ur using ‘dateEntry’ for every loop, so it just overwrites. try something like this:

let myDates = {}
for (let i = 0; i < bigList.length; i++) {
myDates[bigList[i].dateInfo] = true
}

this way u get all ur dates as keys. hope it helps!