skip to Main Content

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


  1. Works as it is:

    const foo = {};
    
    foo.bar = {
      ...foo.bar,
      baz: true
    };
    
    console.log(foo);
    Login or Signup to reply.
  2. 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 ?? {})

    Login or Signup to reply.
  3. You could use the nullish coalescing assignment (??=)operator:

    (foo.bar ??= {}).baz = true;
    

    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:

    foo.bar ??= {};
    foo.bar.baz = true;
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search