How can I simplify this code so that the long property name store.user[userId].order[orderId].items is only specified once?
if (!store.user[userId].order[orderId].items) store.user[userId].order[orderId].items = new Set();
if (store.user[userId].order[orderId].items.has('apples')) store.user[userId].order[orderId].items.add('oranges');
I have a really long object property that makes the code difficult to read. I would like to use a variable as an alias to simplify the code, like this:
let items = store.user[userId].order[orderId].items;
if (items.has('apples')) items.add('oranges');
However if the property hasn't yet been set, I get errors. So I need to define a default object:
let items = store.user[userId].order[orderId].items || new Set();
if (items.has('apples')) items.add('oranges');
However while this works on an existing object, if the new Set() was called then I still need to put the new instance back into the lengthy object to persist it:
let items = store.user[userId].order[orderId].items || new Set();
if (!store.user[userId].order[orderId].items) store.user[userId].order[orderId].items = items;
if (items.has('apples')) items.add('oranges');
Which kind of defeats the purpose.
Is there a way I can use this variable as an alias for the longer property, while supplying and setting a default value if the property doesn't exist yet, but such that I only need to specify the long property name once?
While my example case here is a bit contrived, I encounter this situation a lot when I am looping through data. The same code runs on each iteration but as it encounters different incoming data, it needs to add to existing structures or create them if they don't exist yet - so creating all the properties up front isn't really an option, as you don't know which properties to create until you're in the middle of processing the data.
In case you're accessing an object that might be nested inside optional undefined, use this method.
To set a nullish coalescing (put a value if the variable null or undefined) use this:
let a = bla.bla.mightByNullOrUndefined?.obj?.nested
a ??= somethingElse