如何在 JavaScript 中创建字典并动态添加键值对
来自帖子:
我正在尝试做与那篇文章相同的事情。唯一的问题是我不知道预先的键和值是什么。所以我需要能够动态添加键和值对,但我不知道该怎么做。
如何创建该对象并动态添加键值对?
我试过了:
var vars = [{key:"key", value:"value"}];
vars[0].key = "newkey";
vars[0].value = "newvalue";
但这不起作用。
From post:
Sending a JSON array to be received as a Dictionary<string,string>,
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.
How can I 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
使用:
基本上,您正在创建一个具有两个属性(称为
key
和value
)的对象文字并插入它(使用push()
)进入数组。这不会创建“正常”JavaScript 对象文字(又名地图、又名散列、又名字典)。
然而,它正在创建 OP 要求的结构(在链接到的另一个问题中对此进行了说明),它是一个对象文字数组,每个数组都有
key
和value
属性。不要问我为什么需要这种结构,但这是我们所要求的。但是,但是,如果你想要一个普通的 JavaScript 对象 - 而不是 OP 要求的结构 - 请参阅 tcll 的答案,尽管如果您只有作为有效 JavaScript 名称的简单键,那么括号表示法有点麻烦。您可以这样做:
或者在创建对象后使用常规点符号来设置属性:
如果您的键中包含空格、特殊字符或其他内容,您确实需要括号符号像那样。例如:
如果您的键是动态的,您还需要括号表示法:
请注意,键(属性名称)始终是字符串,并且非字符串值在用作键时将被强制为字符串。例如,
Date
对象被转换为其字符串表示形式:但请注意,这不一定“正常工作”,因为许多对象将具有类似
“[object Object]” 的字符串表示形式
这并不构成非唯一的密钥。因此,请注意以下内容:尽管
objA
和objB
是完全不同且独特的元素,但它们都具有相同的基本字符串表示形式:"[object Object]"
。Date
之所以没有这样的行为,是因为Date
原型有一个自定义的toString
方法,该方法会覆盖默认的字符串表示形式。您也可以这样做:(请注意,由于上面使用了随机数字,因此仍然很容易发生名称冲突。这只是为了说明
toString
的实现。)因此,当尝试使用对象作为键时,JavaScript 将使用对象自己的 toString 实现(如果有),或者使用默认的字符串表示形式。
Use:
Basically, you're creating an object literal with two properties (called
key
andvalue
) and inserting it (usingpush()
) into the array.This does not create a "normal" JavaScript object literal (aka map, aka hash, aka dictionary).
It is however 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
key
andvalue
properties. Don't ask me why that structure was required, but it's the one that was asked for.But, but, if what you want in a plain JavaScript object - and not the 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 JavaScript names. You can just do this:
Or use regular dot-notation to set properties after creating an object:
You do want the bracket notation if you've got keys that have spaces in them, special characters, or things like that. E.g:
You also want bracket notation if your keys are dynamic:
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
Date
object gets converted to its string representation: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:Despite
objA
andobjB
being completely different and unique elements, they both have the same basic string representation:"[object Object]"
.The reason
Date
doesn't behave like this is that theDate
prototype has a customtoString
method which overrides the default string representation. And you can do the same:(Note that since the above uses a random number, name collisions can still occur very easily. It's just to illustrate an implementation of
toString
.)So when trying to use objects as keys, JavaScript will use the object's own
toString
implementation, if any, or use the default string representation.使用:
它的工作方式就像 Python :)
控制台输出:
Use:
It works just like Python :)
Console output:
就像这样简单:
或
然后
It’s as simple as:
or
Then
既然您已经声明您想要一个字典对象(并且不是数组,就像我假设有些人理解的那样),我认为这就是您所追求的:
Since you've stated that you want a dictionary object (and not an array like I assume some understood) I think this is what you are after:
JavaScript 的
Object
本身就像一本字典。无需重新发明轮子。小提琴
JavaScript's
Object
is in itself like a dictionary. No need to reinvent the wheel.Fiddle
您可以将地图与
Map
结合使用,像这样:You can use maps with
Map
, like this:使用 ES6,您可以执行以下操作:
With ES6, you can do this:
Old Way (vanilla JavaScript)
我碰巧遇到这个问题寻找类似的东西。它为我提供了足够的信息来运行测试以获得我想要的答案。因此,如果其他人想知道如何在 JavaScript 对象中动态添加或查找 {key: 'value'} 对,此测试应该告诉您可能需要知道的所有信息。
输出
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.
output
在现代 JavaScript (ES6/ES2015) 中,应该使用字典的Map数据结构。 ES6 中的 Map 数据结构允许您使用任意值作为键。
在您仍在使用 ES5 时,正确的创建方法字典是通过以下方式创建没有原型的对象。
创建没有原型对象的字典有很多优点。以下关于该主题的博客文章值得一读。
字典模式
对象作为地图
In modern JavaScript (ES6/ES2015), one should use the Map data structure for a dictionary. The Map data structure in ES6 lets you use arbitrary values as keys.
In you are still using ES5, the correct way to create dictionary is to create object without a prototype in the following way.
There are many advantages of creating a dictionary without a prototype object. The below blog posts are worth reading on this topic.
dict-pattern
objects-as-maps
首先全局初始化数组:
将对象添加到字典中
输出:
从字典中更新对象
输出:
从字典中删除对象
输出:
First initialise the array globally:
Add the object into the dictionary
Output:
Update the object from the dictionary
Output:
Delete an object from the dictionary
Output:
您可以创建一个字典类,以便可以轻松地与字典列表进行交互:
You could create a class Dictionary so you can interact with the Dictionary list easily:
对
var dict = {}
的改进是使用var dict = Object.create(null)
。这将创建一个空对象,不将
Object.prototype
作为其原型。An improvement on
var dict = {}
is to usevar dict = Object.create(null)
.This will create an empty object that does not have
Object.prototype
as its prototype.使用单行代码创建键值对:
以及一些迭代器函数,例如
reduce
来动态地将数组转换为字典Use a one-liner for creating a key value pair:
And some iterator function like
reduce
to dynamically convert an array to a dictionary我遇到了这个问题......但是在 for 循环中。顶级解决方案不起作用(当使用变量(而不是字符串)作为推送函数的参数时),其他解决方案没有考虑基于变量的键值。我很惊讶这种方法(这在 PHP 中很常见)有效......
I ran into this problem... but within a for loop. The top solution did not work (when using variables (and not strings) for the parameters of the push function), and the others did not account for key values based on variables. I was surprised this approach (which is common in PHP) worked...
如果有人需要动态创建字典对象,您可以使用以下代码片段
In case if someone needs to create a dictionary object dynamically you can use the following code snippet
您可以像这样初始化字典
并像这样访问它
You can initialize the dictionary like
And access it like