带有子对象的javascript对象 - 如何正确使用它

时间:2014-10-27 04:45:49

标签: javascript dictionary nested

我已经看到在Python中可以有一个命名元组来存储和检索与键值相关的值,如下所示:

REQUIRED_FIELDS = {
    0: RequiredFields(LocalityDisplay=True, LocalityRequired=False, RegionDisplay=True, RegionRequired=False, PostcodeDisplay=True, PostcodeRequired=False),
    1: RequiredFields(LocalityDisplay=False, LocalityRequired=False, RegionDisplay=True, RegionRequired=True, PostcodeDisplay=True, PostcodeRequired=True),
    2: RequiredFields(LocalityDisplay=True, LocalityRequired=True, RegionDisplay=False, RegionRequired=False, PostcodeDisplay=True, PostcodeRequired=True),
    3: RequiredFields(LocalityDisplay=True, LocalityRequired=True, RegionDisplay=False, RegionRequired=False, PostcodeDisplay=True, PostcodeRequired=True),
    ..........
}

我试图在javascript中复制上面的代码。在搜索中,我发现了一个模糊且不太有用的参考javascript"嵌套字典"但我找不到任何例子。我试过搜索其他变种,但是空白了。这种方法是否会被称为嵌套字典"还是用另一个名字?

我希望有人能够对这个主题有所了解,并看看我怀疑这个javascript嵌套词典语法可能会如何设置的例子。

var addressNestedDictionary = {
    0: {"LocalityDisplay": 'True', "LocalityRequired": "False", "RegionDisplay": "True", "RegionRequired": "False", "PostcodeDisplay": "True", "PostcodeRequired": "False"}, 
    1: {"LocalityDisplay": "False", "LocalityRequired": "False", "RegionDisplay": "True", "RegionRequired": "True", "PostcodeDisplay": "True", "PostcodeRequired": "True"},
    2: {"LocalityDisplay": "True", "LocalityRequired": "True", "RegionDisplay": "False", "RegionRequired": "False", "PostcodeDisplay": "True", "PostcodeRequired": "True"},
    3: {"LocalityDisplay": "True", "LocalityRequired": "True", "RegionDisplay": "False", "RegionRequired": "False", "PostcodeDisplay": "True", "PostcodeRequired": "True"},
    ........
};

如果上述方法正确,我将如何调用嵌套字典?

1 个答案:

答案 0 :(得分:1)

JavaScript包含对象,而不是字典。您可以通过两种方式实例化对象:

var myObj = {};
var myObj = new Object();

对象允许您访问其命名属性。您可以在创建期间设置属性:

var myObj = {
    0 : "fun",
    test : [1, 2, 3],
    "delete" : "you need to surround keywords, like delete, in quotes",
    "if" : "otherwise, the quotes are optional"
}

或稍后:

myObj.anArray = [];

对象属性甚至可以是另一个对象!

myObj.subObject = {};

您可以通过两种方式访问​​这些属性:

myObj["subObject"]    // equal to {}
myObj.subObject       // equal to {}

在您的情况下,您将使用以下命令访问子对象:

addressNestedDictionary[0]
/* returns
   {
    "LocalityDisplay": 'True',
    "LocalityRequired": "False",
    "RegionDisplay": "True",
    "RegionRequired": "False",
    "PostcodeDisplay": "True", "PostcodeRequired": "False"
   }
*/

请注意我使用addressNestedDictionary[0]的方式。这是因为addressNestedDictionary.0将是语法错误 - 它将被错误地解析。但是,符号,括号和点都表示完全相同的事情。