如何有效地用许多静态键/值对填充 Javascript 对象文字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14711956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:42:33  来源:igfitidea点击:

How to fill a Javascript object literal with many static key/value pairs efficiently?

javascriptobject-literalstatic-initialization

提问by Jér?me Verstrynge

The typical way of creating a Javascript object is the following:

创建 Javascript 对象的典型方法如下:

var map = new Object();
map[myKey1] = myObj1;
map[myKey2] = myObj2;

I need to create such a map where both keys and values are Strings. I have a large but static set of pairs to add to the map.

我需要创建这样一个映射,其中键和值都是字符串。我有一组大而静态的对要添加到地图中。

Is there any way to perform something like this in Javascript:

有什么方法可以在 Javascript 中执行这样的操作:

var map =  { { "aaa", "rrr" }, { "bbb", "ppp" } ... };

or do I have to perform something like this for each entry:

还是我必须为每个条目执行这样的操作:

map["aaa"]="rrr";
map["bbb"]="ppp";
...

Basically, remaining Javascript code will loop over this map and extract values according to criterias known 'at runtime'. If there is a better data structure for this looping job, I am interested too. My objective is to minimize code.

基本上,剩余的 Javascript 代码将遍历此映射并根据“运行时”已知的标准提取值。如果这个循环作业有更好的数据结构,我也很感兴趣。我的目标是最小化代码。

回答by Nitin

In ES2015 a.k.a ES6 version of JavaScript, a new datatype called Mapis introduced.

在 ES2015 又名 ES6 版本的 JavaScript 中,Map引入了一种名为的新数据类型。

let map = new Map([["key1", "value1"], ["key2", "value2"]]);
map.get("key1"); // => value1

check this referencefor more info.

查看此参考以获取更多信息。

回答by zzzzBov

JavaScript's object literal syntax, which is typically used to instantiate objects (seriously, no one uses new Objector new Array), is as follows:

JavaScript 的对象字面量语法,通常用于实例化对象(说真的,没有人使用new Objectnew Array),如下所示:

var obj = {
    'key': 'value',
    'another key': 'another value',
     anUnquotedKey: 'more value!'
};

For arrays it's:

对于数组,它是:

var arr = [
    'value',
    'another value',
    'even more values'
];

If you need objects within objects, that's fine too:

如果您需要对象中的对象,那也很好:

var obj = {
    'subObject': {
        'key': 'value'
    },
    'another object': {
         'some key': 'some value',
         'another key': 'another value',
         'an array': [ 'this', 'is', 'ok', 'as', 'well' ]
    }
}

This convenient method of being able to instantiate static data is what led to the JSON data format.

这种能够实例化静态数据的便捷方法导致了JSON 数据格式

JSON is a little more picky, keys must be enclosed in double-quotes, as well as string values:

JSON 有点挑剔,键必须用双引号括起来,还有字符串值:

{"foo":"bar", "keyWithIntegerValue":123}

回答by Christoph

It works fine with the object literal notation:

它适用于对象文字符号:

var map = { key : { "aaa", "rrr" }, 
            key2: { "bbb", "ppp" } // trailing comma leads to syntax error in IE!
          }

Btw, the common way to instantiate arrays

顺便说一句,实例化数组的常用方法

var array = [];
// directly with values:
var array = [ "val1", "val2", 3 /*numbers may be unquoted*/, 5, "val5" ];

and objects

和对象

var object = {};

Also you can do either:

您也可以执行以下任一操作:

obj.property     // this is prefered but you can also do
obj["property"]  // this is the way to go when you have the keyname stored in a var

var key = "property";
obj[key] // is the same like obj.property

回答by MKS

Give this a try:

试试这个:

var map = {"aaa": "rrr", "bbb": "ppp"};

回答by ZER0

The syntax you wrote as first is not valid. You can achieve something using the follow:

您首先编写的语法无效。您可以使用以下方法实现某些目标:

var map =  {"aaa": "rrr", "bbb": "ppp" /* etc */ };