最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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;
发布评论

评论列表(0)

  1. 暂无评论