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

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

3

Bracket notation requires the key be a string:

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

Or just use dot notation:

myDict.key1[identifier] = info;

6 Comments

This would have been my answer too, not sure why someone thought it was bad.
key1 is probably a variable to be fair.
I know @Morphyish, but the fact that they have not defined it has caused the error.
Since identifier is a variable defined above myDict.key1[identifier] = info would be the correct solution
@JackBashford my own bet is on the fact that key1 has no associated value in the dict when they are trying to update its property ;D
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.