I have a dictionary of the following structure:
myDict = {key1:{innerKey1:innerValue1, innerKey2:innerValue2}, key2:{},...}
Based on: How can I add a key/value pair to a JavaScript object?
I tried to add inner key/value pairs like this:
someArray=['foo','bar']
var identifier = someArray[0]
var info = someArray[1]
myDict[key1][identifier] = info;
Or like this:
myDict[key1].identifier = info;
But I get the error 'cannot set property of undefined'. I think this is due to the identifier not being defined in myDict yet, but I cannot figure out how to achieve this:
myDict = {key1:{innerkey1:innerValue1, innerKey2: innerValue2, foo:bar,...}, key2:{},...}
Please note: I know in this example the assignment of variables is not necessary. I need to figure out the concept for a bigger, more complex project and this is the minimum "non-working" example.
Thanks in advance :)
From your snippet, key1
doesn't seem to be defined.
You also want to make sure that the object is defined before trying to access it
someArray=['foo','bar']
var identifier = someArray[0]
var info = someArray[1]
if (!myDict[key1]) myDict[key1] = {};
myDict[key1][identifier] = info;