如何dynamic创build字典并添加键值对

来自:

发送一个JSON数组作为Dictionary <string,string>接收

我正在试图做同样的事情,那个职位。 唯一的问题是,我不知道什么是关键和价值观。 所以我需要能够dynamic地添加键和值对,我不知道该怎么做。

有谁知道如何创build该对象并dynamic添加键值对?

我试过了:

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

但是这不起作用。

 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 

基本上,你正在创build一个具有2个属性(称为keyvalue )的对象字面值并将其插入(使用push() )到数组中。


编辑:所以差不多5年后,这个答案变得downvotes,因为它不是创build一个“正常的”JS对象文字(又名地图,又名哈希,又名字典)。
然而,它创build了OP要求的结构(以及与其相关的另一个问题中所示的结构),它是一组对象文字 ,每个对象具有keyvalue属性。 不要问为什么这个结构是必需的,但它是被要求的。

但是,如果你想要一个普通的JS对象而不是 OP所要求的结构 – 请参阅tcll的答案 ,尽pipe如果你只有简单的键是有效的JS名称,括号表示有点麻烦。 你可以这样做:

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

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

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

如果你的钥匙里有空格,特殊字符或者类似的东西,你可以使用括号。 例如:

 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"; 

如果您的密钥是dynamic的,您还需要使用括号表示法:

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

请注意,键(属性名称)始终是string,而非string值在被用作键时将被强制转换为string。 例如Date对象被转换为其string表示forms:

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

但是请注意,这不一定是“正常工作”,因为许多对象将具有像"[object Object]"这样的string表示forms,这不会形成非唯一的关键字。 所以要小心这样的事情:

 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" } 

尽pipeobjAobjB是完全不同且独特的元素,但它们都具有相同的基本string表示forms: "[object Object]"

Date行为不像这样的原因是Date原型有一个自定义的toString方法,它覆盖了默认的string表示。 你也可以这样做:

 // 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" // } 

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

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

 var dict = {}; dict['key'] = "testing"; console.log(dict); 

工作就像python:)

控制台输出:

 Object {key: "testing"} 

其如此简单:

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

要么

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

然后

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

既然你已经说过你想要一个字典对象(而不是像我假设有一些理解的数组 ),我认为这是你在之后:

 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 

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 } 

小提琴

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

 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); 

产量

 initialValue { initialkey: 'initialValue', something: 'value1', somethingElse: 'value2' } 
 var dictionary = {};//create new object dictionary["key1"] = value1;//set key1 var key1 = dictionary["key1"];//get key1 

我碰到这个问题..但在一个for循环。 最上面的解决scheme不起作用(对推式函数的参数使用variables(而不是string)),而其他解决scheme没有考虑基于variables的关键值。 我很惊讶这种方法(这是常见的PHP)工作..

  // example dict/json var iterateDict = {'record_identifier': {'content':'Some content','title':'Title of my Record'}, 'record_identifier_2': {'content':'Some different content','title':'Title of my another Record'} }; var array = []; // key to reduce the 'record' to var reduceKey = 'title'; for(key in iterateDict) // ultra-safe variable checking... if(iterateDict[key] !== undefined && iterateDict[key][reduceKey] !== undefined) // build element to new array key array[key]=iterateDict[key][reduceKey]; 

这将有助于了解你的最终结果是什么,但我认为这是你想要的:

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

var dict = {}的改进是使用var dict = Object.create(null)

这将创build一个没有 Object.prototype的空对象,因为它的原型。

 var dict1 = {}; if (dict1["toString"]){ console.log("Hey, I didn't put that there!") } var dict2 = Object.create(null); if (dict2["toString"]){ console.log("This line won't run :)") }