从文章:

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

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

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

我试过了:

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

但这行不通。


当前回答

创建键值对的一行代码怎么样?

let result = { ["foo"]: "some value" };

还有一些迭代器函数,比如reduce,可以动态地将数组转换为字典

Var选项= [ {key: "foo",值:1}, {key: "bar",值:{id: 2,名称:"two"}}, {key: "baz", value: {["active"]: true}}, ]; Var result = options。Reduce((累加器,电流)=> { 蓄电池(电流。键]= current.value; 返回蓄电池; }, {}); console.log(结果);

其他回答

我遇到了这个问题。但是在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];
var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1

创建键值对的一行代码怎么样?

let result = { ["foo"]: "some value" };

还有一些迭代器函数,比如reduce,可以动态地将数组转换为字典

Var选项= [ {key: "foo",值:1}, {key: "bar",值:{id: 2,名称:"two"}}, {key: "baz", value: {["active"]: true}}, ]; Var result = options。Reduce((累加器,电流)=> { 蓄电池(电流。键]= current.value; 返回蓄电池; }, {}); console.log(结果);

首先全局初始化数组

var dict = []

将对象添加到字典

dict.push(
     { key: "One",value: false},
     { key: "Two",value: false},
     { key: "Three",value: false});

Output : 
   [0: {key: "One", value: false}
    1: {key: "Two", value: false}
    2: {key: "Three", value: false}]

从字典中更新对象

Object.keys(dict).map((index) => {        
  if (index == 1){
    dict[index].value = true
  }
});

Output : 
   [0: {key: "One", value: false},
    1: {key: "Two", value: true},
    2: {key: "Three", value: false}]

从字典中删除对象

Object.keys(dict).map((index) => {              
      if (index == 2){
        dict.splice(index)
      }
    });

Output : 
    [0: {key: "One", value: false},
     1: {key: "Two", value: true}]

很简单:

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