Javascript 如何创建字典并动态添加键值对?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7196212/
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 01:18:43  来源:igfitidea点击:

How to create dictionary and add key–value pairs dynamically?

javascriptdictionarykey-value

提问by KenEucker

From post:

来自帖子:

Sending a JSON array to be received as a Dictionary<string,string>

发送要作为 Dictionary<string,string> 接收的 JSON 数组

I'm trying to do this same thing as that post. The only issue is that I don't know what the keys and the values are upfront. So I need to be able to dynamically add the key and value pairs and I don't know how to do that.

我正在尝试做与该帖子相同的事情。唯一的问题是我不知道键和值是什么。所以我需要能够动态添加键和值对,但我不知道该怎么做。

Does anyone know how to create that object and add key value pairs dynamically?

有谁知道如何创建该对象并动态添加键值对?

I've tried:

我试过了:

var vars = [{key:"key", value:"value"}];
vars[0].key = "newkey";
vars[0].value = "newvalue";

But that doesn't work.

但这不起作用。

回答by Flambino

var dict = []; // create an empty array

dict.push({
    key:   "keyName",
    value: "the value"
});
// repeat this last part as needed to add more key/value pairs

Basically, you're creating an object literal with 2 properties (called keyand value) and inserting it (using push()) into the array.

基本上,您正在创建一个具有 2 个属性(称为keyand value)的对象文字并将其(使用push())插入到数组中。



Edit:So almost 5 years later, this answer is getting downvotes because it's not creating an "normal" JS object literal (aka map, aka hash, aka dictionary).
It ishowever creating the structure that OP asked for (and which is illustrated in the other question linked to), which is an array of object literals, each with keyand valueproperties. Don't ask me why that structure was required, but it's the one that was asked for.

编辑:所以差不多 5 年后,这个答案被否决了,因为它没有创建“正常”的 JS 对象文字(又名地图,又名哈希,又名字典)。然而,
正在创建 OP 要求的结构(并且在链接到的另一个问题中进行了说明),这是一个对象文字数组,每个对象文字都具有keyvalue属性。不要问我为什么需要这种结构,但它是被要求的结构。

But, but, if what you want in a plain JS object - and notthe structure OP asked for - see tcll's answer, though the bracket notation is a bit cumbersome if you just have simple keys that are valid JS names. You can just do this:

但是,但是,如果您在普通 JS 对象中想要什么 - 而不是OP 要求的结构 - 请参阅tcll 的答案,尽管如果您只有有效 JS 名称的简单键,则括号表示法有点麻烦。你可以这样做:

// object literal with properties
var dict = {
  key1: "value1",
  key2: "value2"
  // etc.
};

Or use regular dot-notation to set properties after creating an object:

或者在创建对象后使用常规点符号来设置属性:

// empty object literal with properties added afterward
var dict = {};
dict.key1 = "value1";
dict.key2 = "value2";
// etc.

You dowant the bracket notation if you've got keys that have spaces in them, special characters, or things like that. E.g:

如果您的键中有空格、特殊字符或类似的东西,您确实需要括号表示法。例如:

var dict = {};

// this obviously won't work
dict.some invalid key (for multiple reasons) = "value1";

// but this will
dict["some invalid key (for multiple reasons)"] = "value1";

You also want bracket notation if your keys are dynamic:

如果您的键是动态的,您还需要括号表示法:

dict[firstName + " " + lastName] = "some value";

Note that keys (property names) are always strings, and non-string values will be coerced to a string when used as a key. E.g. a Dateobject gets converted to its string representation:

请注意,键(属性名称)始终是字符串,非字符串值在用作键时将被强制转换为字符串。例如,一个Date对象被转换为它的字符串表示:

dict[new Date] = "today's value";

console.log(dict);
// => {
//      "Sat Nov 04 2016 16:15:31 GMT-0700 (PDT)": "today's value"
//    }

Note however that this doesn't necessarily "just work", as many objects will have a string representation like "[object Object]"which doesn't make for a non-unique key. So be wary of something like:

但是请注意,这不一定“只是工作”,因为许多对象将具有字符串表示形式,例如"[object Object]"不会生成非唯一键。所以要警惕类似的事情:

var objA = { a: 23 },
    objB = { b: 42 };

dict[objA] = "value for objA";
dict[objB] = "value for objB";

console.log(dict);
// => { "[object Object]": "value for objB" }

Despite objAand objBbeing completely different and unique elements, they both have the same basic string representation: "[object Object]".

尽管objAobjB是完全不同的,独特的元素,它们都具有相同的基本字符串表示:"[object Object]"

The reason Datedoesn't behave like this is that the Dateprototype has a custom toStringmethod which overrides the default string representation. And you can do the same:

Date行为不像这样的原因是Date原型具有toString覆盖默认字符串表示的自定义方法。你也可以这样做:

// a simple constructor with a toString prototypal method
function Foo() {
  this.myRandomNumber = Math.random() * 1000 | 0;
}

Foo.prototype.toString = function () {
  return "Foo instance #" + this.myRandomNumber;
};

dict[new Foo] = "some value";

console.log(dict);
// => {
//      "Foo instance #712": "some value"
//    }

(Note that since the above uses a randomnumber, name collisions can still occur very easily. It's just to illustrate an implementation of toString.)

(请注意,由于上面使用了随机数,因此仍然很容易发生名称冲突。只是为了说明 的实现toString。)

So when trying to use objects as keys, JS will use the object's own toStringimplementation, if any, or use the default string representation.

所以当尝试使用对象作为键时,JS 会使用对象自己的toString实现,如果有的话,或者使用默认的字符串表示。

回答by Tcll

var dict = {};

dict['key'] = "testing";

console.log(dict);

works just like python :)

就像 python 一样工作 :)

console output:

控制台输出:

Object {key: "testing"} 

回答by Simon Sarris

Its as simple as:

它很简单:

var blah = {}; // make a new dictionary (empty)

or

或者

var blah = {key: value, key2: value2}; // make a new dictionary with two pairs 

then

然后

blah.key3 = value3; // add a new key/value pair
blah.key2; // returns value2
blah['key2']; // also returns value2

回答by ZenMaster

Since you've stated that you want a dictionary object (and not an arraylike I assume some understood) I think this is what you are after:

既然你已经声明你想要一个字典对象(而不是像我认为有些人理解的数组),我认为这就是你所追求的:

var input = [{key:"key1", value:"value1"},{key:"key2", value:"value2"}];

var result = {};

for(var i = 0; i < input.length; i++)
{
    result[input[i].key] = input[i].value;
}

console.log(result); // Just for testing

回答by Jani Hyyti?inen

JavaScript's Objectisin itself like a dictionary. No need to reinvent the wheel.

JavaScript的Object本身像一本字典。无需重新发明轮子。

var dict = {};

// Adding key-value -pairs
dict['key'] = 'value'; // Through indexer
dict.anotherKey = 'anotherValue'; // Through assignment

// Looping through
for (var item in dict) {
  console.log('key:' + item + ' value:' + dict[item]);
  // Output
  // key:key value:value
  // key:anotherKey value:anotherValue
}

// Non existent key
console.log(dict.notExist); // undefined

// Contains key?
if (dict.hasOwnProperty('key')) {
  // Remove item
  delete dict.key;
}

// Looping through
for (var item in dict) {
  console.log('key:' + item + ' value:' + dict[item]);
  // Output
  // key:anotherKey value:anotherValue
}

Fiddle

小提琴

回答by Preetham Kumar P

You can use maps with Map, like this:

您可以将地图与 一起使用Map,如下所示:

var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');

回答by user2301449

I happened to walk across this question looking for something similar. It gave me enough info to run a test to get the answer I wanted. So if anyone else wants to know how to dynamically add to or lookup a {key: 'value'} pair in a JavaScript object, this test should tell you all you might need to know.

我碰巧遇到了这个问题,正在寻找类似的东西。它给了我足够的信息来运行测试以获得我想要的答案。因此,如果其他人想知道如何在 JavaScript 对象中动态添加或查找 {key: 'value'} 对,此测试应该会告诉您所有您可能需要知道的信息。

var dictionary = {initialkey: 'initialValue'};
var key = 'something';
var key2 =  'somethingElse';
var value = 'value1';
var value2 = 'value2';
var keyInitial = 'initialkey';

console.log(dictionary[keyInitial]);

dictionary[key] =value;
dictionary[key2] = value2;
console.log(dictionary);

output

输出

initialValue
{ initialkey: 'initialValue',
  something: 'value1',
  somethingElse: 'value2' }

回答by SharpCoder

var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1

回答by agonza1

You could create a class Dictionary so you can interact with the Dictionary list easily:

您可以创建一个类 Dictionary,以便您可以轻松地与 Dictionary 列表交互:

class Dictionary {
  constructor() {
    this.items = {};
  }
  has(key) {
    return key in this.items;
  }
  set(key,value) {
    this.items[key] = value;
  }
  delete(key) {
    if( this.has(key) ){
      delete this.items[key]
      return true;
    }
    return false;
  }
}

var d = new Dictionary();
d.set(1, "value1")
d.set(2, "value2")
d.set(3, "value3")
console.log(d.has(2));
d.delete(2);
console.log(d.has(2));

回答by Jyoti Prasad Pal

In modern javascript (ES6/ES2015), one should use Map data structure for dictionary. The Map data structure in ES6 lets you use arbitrary values as keys.

在现代 javascript (ES6/ES2015) 中,应该使用 Map 数据结构作为字典。ES6 中的 Map 数据结构允许您使用任意值作为键。

const map = new Map();
map.set("true", 1);
map.set("false", 0);

In you are still using ES5, the correct way to create dictionary is to create object without a prototype in the following way.

在你还在使用 ES5 的情况下,创建字典的正确方法是按照以下方式创建没有原型的对象。

var map = Object.create(null);
map["true"]= 1;
map["false"]= 0;

There are many advantages of creating a dictionary without a prototype object. Below blogs are worth reading on this topic.

创建没有原型对象的字典有很多优点。关于这个主题,下面的博客值得一读。

dict-pattern

字典模式

objects-as-maps

对象即地图