如何在JavaScript中动态创建字典和添加键值对 [英] How to create dictionary and add key value pairs dynamically in Javascript
问题描述
从帖子
发送要作为字典接收的JSON数组< string,string>
I我试图做同样的事情,唯一的问题是,我不知道什么是钥匙和价值观在前面。所以我需要能够动态添加键和值对,我不知道该怎么做。
有谁知道如何创建该对象并添加键值对动态?
我试过:
var vars = [{key:key,value:value}];
vars [0] .key =newkey;
vars [0] .value =newvalue;
但这不行。
var dict = []; //创建一个空数组
dict.push({
key:keyName,
value:value
});
//根据需要重复此最后一部分以添加更多键/值对
基本上,您正在创建一个具有2个属性(称为 key
和 value
)的对象文字,并插入(使用 push()
)到数组中。
编辑: / strong>所以近5年后,这个答案是得到downvote,因为它不是创建一个正常的JS对象文字(又名地图,又名哈希,也称为字典)。
它是然而创建OP要求的结构(并且在另一个问题链接中被说明),这是一个对象文字数组,每个都有键
和值
属性。不要问我为什么需要这个结构,但是这是被要求的。
但是,如果你想在一个简单的JS对象中 结构OP要求 - 请参阅 tcll的答案,尽管括号符号有点麻烦如果你只是有简单的键是有效的JS名称。您可以这样做:
//对象文字与属性
var dict = {
key1: value1,
key2:value2
//等
};
或者在创建对象后使用常规点表示法设置属性:
//以后添加属性的空对象文字
var dict = {};
dict.key1 =value1;
dict.key2 =value2;
//等
你想要括号的符号如果你有钥匙在其中有空格,特殊字符或类似的东西。例如:
var dict = {};
//这显然不会工作
dict.some无效键(由于多个原因)=value1;
//但这将
dict [一些无效的密钥(因为多个原因)] =value1;
如果您的键是动态的,您还需要括号符号:
dict [firstName ++ lastName] =some value;
请注意,键(属性名称)始终为字符串,非字符串值将被强制为用作键的字符串。例如。一个 Date
对象被转换成其字符串表示形式:
dict [new日期] =今日价值;
$请注意,这并不一定是正常工作,因为许多对象将有一个字符串表示,如
console.log(dict);
// => {
//Sat Nov 04 2016 16:15:31 GMT-0700(PDT):今天的价值
//}
[object Object]
这不是一个非唯一的键。所以要警惕如下:var objA = {a:23},
objB = {b:42 };
dict [objA] =objA的值;
dict [objB] =objB的值;
console.log(dict);
// => {[object Object]:objB的值}
尽管
objA
和objB
完全不同,唯一的元素,它们都具有相同的基本字符串表示形式:[object Object]
。
Date
的原因不像这样, code> Date 原型有一个定制的toString
方法,它覆盖了默认的字符串表示形式。你可以这样做://一个带有toString原型方法的简单构造函数
函数Foo(){
this.myRandomNumber = Math.random()* 1000 | 0;
}
Foo.prototype.toString = function(){
returnFoo instance#+ this.myRandomNumber;
};
dict [new Foo] =some value;
console.log(dict);
// => {
//Foo instance#712:some value
//}
(请注意,由于上述使用了一个随机号码,所以名称冲突仍然可以很容易地发生,这只是为了说明一个
toString
。)
所以当尝试使用对象作为键时,JS将使用对象自己的
toString
实现,如果任何,或使用默认字符串表示。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.
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.
解决方案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
key
andvalue
) and inserting it (usingpush()
) into the array.
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 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 withkey
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 JS 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 JS names. You can just do this:
// 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 do want 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
Date
object gets converted to its string representation: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: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
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:// 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 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, JS will use the object's own
toString
implementation, if any, or use the default string representation.这篇关于如何在JavaScript中动态创建字典和添加键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!