If I want to set a nested property like foo.bar.baz = true
but it’s parent foo.bar
might be undefined
, what’s the best way to do that?
I know I can do this with:
foo.bar = {
...foo.bar,
baz: true
}
but is there a more concise way of doing it?
Thanks!
3
Answers
Works as it is:
You could do:
foo.bar = Object.assign(foo.bar ?? {}, { baz: true })
.Also I wouldn’t consider spread operator used with variables that might be
undefined
as a good practice (although your snippet code won’t end up with run time error).So either way do
foo.bar ?? {}
or...(foo.bar ?? {})
You could use the nullish coalescing assignment (
??=
)operator:But in my opinion, it’s not very readable, and your original code is easier to read. A more readable of the above would be to use:
This is a bit different to your original code, as it will keep the original object reference in
foo.bar
if it already exists, as opposed to always creating a new one.