Galivan
Galivan

Reputation: 5328

Javascript - dynamically adding properties to object results in last value being set for all properties

I am looping some dates , adding them dynamically as properties to an object , and assigning a value to each. The properties are added but they all end up being set to the value assigned at the last iteration.

There is some referencing problem I guess. I'm not sure exactly where the problem is and what to do.

The below is also available in a fiddle with logging.

  let dates = ['2020-04-28','2020-05-3','2020-05-16']
  let pricesObj = {};

var entry = { 
    price: 45,
    time_id: 2
 }

dates.map( date => {

    entry.date = date

    if( !(date in pricesObj)){

      //Add new date entry
      pricesObj[date] = []
      pricesObj[date].push(entry)   //<-- this seems to be assigned to all dates, not just the current

    }

 })
console.log('updating price with obj: ' , JSON.stringify(pricesObj));

The logging shows the object with three date properties, and they all have the last "entry" with the wrong date.

Upvotes: 0

Views: 124

Answers (1)

Snow
Snow

Reputation: 4097

You only created one entry, and then pushing it to different arrays. Create the entries anew each time you need them instead.

dates.forEach(date => {
  if (!(date in pricesObj)) {
    //Add new date entry
    pricesObj[date] = [{
      date,
      price: 45,
      time_id: 2
    }];
  }
});

You're not making a new array for every item in the original dates array, so don't use map. To just iterate, use forEach.

Upvotes: 2

Related Questions