Say i have this object:
test = {
testObj: {
"1": {
"key": "value"
}
}
}
And i want to add values to testObj like so:
test.testObj["2"].key = "my value";
I get error TypeError: Cannot set property 'key' of undefined
Now i do understand that key does not exist yet, but 2 doesn’t exist also, and yet i can set value to it:
test.testObj["2"] = "something";
So what can i do about it?
EDIT
wow i feel stupid for not figuring that out by myself… anyways thank you guys.
Javascript doesn’t know what
test.testObj["2"]should be in this scenario, so it ends up testing it as an existing property:The assignment can only apply to the last part of the structure on the left.
But you can tell it what it is by creating the object first:
Or in a single step: