Search code examples
javascriptjavascript-objects

Is there a direct way to deeply nest in a JavaScript object?


In other words: can JavaScript automatically create object parents?

In an example where "testObject" is already created...

let testObject = {}

...this throws an error...

testObject.parent.child.grandchild = { foo: 'ya' };

This works but is a lot of code...

  testObject.parent = {};
  testObject.parent.child = {};
  testObject.parent.child.grandchild = { foo: 'ya' };

Things get more complicated if the middle generation might have data, so checks are needed...

  if (!testObject.parent) {
    testObject.parent = {};
  }
  if (!testObject.parent.child) {
    testObject.parent.child = {};
  }
  testObject.parent.child.grandchild = { foo: 'ya' };

What I'm looking for is a direct way to create middle generations in an object if they're not already created. Is this possible with less coding than these examples? (Sorry in advance if this is a duplicate question!)


Solution

  • ??= operator:

    const testObject = {};
    
    ((testObject.parent ??= {}).child ??= {}).grandchild = {foo: 'ya'};
    
    console.log(testObject);