dictionary - Javascript: Add keyvalue pairs in nested dict; key and value are variables - Stack Overflow

I have a dictionary of the following structure:myDict = {key1:{innerKey1:innerValue1, innerKey2:innerVa

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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;

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

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信