0

Consider the following example:

const initObject = { a: 2, b: 3, c: 4 };

let shouldChangeB = false;

const newB = 4

const newObject = {
  ...initObject,
  //shouldChangeB && b: newB - syntax error
  //b: shouldChangeB ? newB : undefined - sets b to undefined
};

const newObject = shouldChangeB ? {
  ...initObject, b: newB
} : initObject;
//would work, but dirty if there's may keys we want to change by conditional

Is there a smart way to solve this problem?

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64
  • Cant you just use `if(shouldChangeB) newObject.b = newB` on a separate line? That way you don't edit the object if you don't need to. – Kobe Aug 15 '19 at 09:48
  • Yeah, I'd prefer the separate line version too - it might look a bit worse because the object isn't defined all at once, but it's still a lot more readable than the other options IMO – CertainPerformance Aug 15 '19 at 09:49

0 Answers0