Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading