Issue
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.upsert(myKey, 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 = '1234';
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]
Solution
The nullish-coalescing assignment operator forms an expression. You don't have to put it in a separate statement (line):
(myObj[myKey] ??= []).push(myValue);
Answered By - Bergi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.