2

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

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Shushiro
  • 577
  • 1
  • 9
  • 32

2 Answers2

4

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;
Morphyish
  • 3,932
  • 8
  • 26
3

Bracket notation requires the key be a string:

myDict["key1"][identifier] = info;

Or just use dot notation:

myDict.key1[identifier] = info;
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79