[英]Javascript: Add key/value pairs in nested dict; key and value are variables
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? 基于: 如何将键/值对添加到JavaScript对象?
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' . 但是我得到了错误“无法设置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中定义标识符,但是我无法弄清楚如何实现此目的:
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 :) 提前致谢 :)
Bracket notation requires the key be a string: 括号表示法要求键为字符串:
myDict["key1"][identifier] = info;
Or just use dot notation: 或只使用点符号:
myDict.key1[identifier] = info;
From your snippet, key1
doesn't seem to be defined. 从您的代码段来看,
key1
似乎没有定义。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.