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!)
undefinedvalue the error thrown isUncaught TypeError: Cannot read properties of undefined. The point being that if you use a property name not defined in an object, its value will beundefinedindeed and you cannot have success when you attempt to access its own properties further. You may be interested to Optional chaining (?.)