I have an object with ids for keys that I want to conditionally add an array to. I could do this, but I don’t want this code repeated 3 times in my function:
const myObj = {};
const myKey = '1233';
const myValue = true;
if (!(myKey in myObj)) {
myObj[myKey] = [];
}
myObj[myKey].push(myValue);
I would like to do something myObj[myKey].upsert(myValue)
, but modifying the Object prototype currently causes performance issues. Using Object.create (as suggested) causes a lot of TypeScript issues in my application and I was casting my object back to one without the upsert method to pass it along which felt bloated and wrong.
So I opted to use the nullish coelescing assignment operator in my code:
const myObj = {};
const myKey = '1233';
const myValue = true;
myObj[myKey] ??= [];
myObj[myKey].push(myValue);
and that works great! But, is it possible to do this in one line?
I was thinking something like this might work, but no:
myObj[myKey] ??= [...myObj[myKey], myValue]