0

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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that works. So I couldn't create the entry variable outside of the loopSlightly puzzling, but, nice tips!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.