2

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!)

2
  • 1
    lodash.com/docs/4.17.15#set Commented Feb 8, 2024 at 22:25
  • you call them generations but those are actually properties of objects.. and if you try access to properties of a an undefined value the error thrown is Uncaught TypeError: Cannot read properties of undefined. The point being that if you use a property name not defined in an object, its value will be undefined indeed and you cannot have success when you attempt to access its own properties further. You may be interested to Optional chaining (?.) Commented Feb 8, 2024 at 22:29

1 Answer 1

3

??= operator:

const testObject = {};

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

console.log(testObject);

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Alexander, that's an elegant solution!
For future readers: Alexander's suggestion to use the ??= (nullish coalescing assignment) operator seems to be working well for me. Further reference can be found here... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.