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 plex project and this is the minimum "non-working" example.
Thanks in advance :)
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 plex project and this is the minimum "non-working" example.
Thanks in advance :)
Share Improve this question edited Aug 9, 2019 at 9:25 Jack Bashford 44.2k11 gold badges55 silver badges82 bronze badges asked Aug 9, 2019 at 9:24 ShushiroShushiro 5821 gold badge11 silver badges35 bronze badges2 Answers
Reset to default 4From 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;
Bracket notation requires the key be a string:
myDict["key1"][identifier] = info;
Or just use dot notation:
myDict.key1[identifier] = info;
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745116924a4612184.html
评论列表(0条)