从文章:

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

我试图做同样的事情,因为那篇文章,唯一的问题是,我不知道什么键和值是前面。我需要动态添加键和值对,我不知道怎么做。

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

我试过了:

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

但这行不通。


当前回答

var dict = {};

dict['key'] = "testing";

console.log(dict);

就像python一样工作:)

控制台输出:

Object {key: "testing"} 

其他回答

var dict = {};

dict['key'] = "testing";

console.log(dict);

就像python一样工作:)

控制台输出:

Object {key: "testing"} 

我碰巧在寻找类似的东西时遇到了这个问题。它给了我足够的信息来进行测试,以得到我想要的答案。因此,如果有人想知道如何动态地添加或查找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);

输出

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

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

这将创建一个没有object的空对象。原型就是原型。

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

我遇到了这个问题。但是在for循环中。上面的解决方案不起作用(当使用变量(而不是字符串)作为push函数的参数时),其他解决方案没有考虑基于变量的键值。我很惊讶这种方法(这是常见的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];

你可以在Map中使用地图,像这样:

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