首页 文章

如何动态创建字典和添加键值对?

提问于
浏览
224

从帖子:

Sending a JSON array to be received as a Dictionary<string,string>

我正在尝试做同样的事情 . 唯一的问题是我不知道密钥和值是什么 . 所以我需要能够动态添加键和值对,我不知道该怎么做 .

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

我试过了:

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

但这不起作用 .

13 回答

  • 1

    它很简单:

    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
    
  • 6

    既然你已经声明你想要一个字典对象(和 not an array ,就像我假设一些人理解的那样),我认为这就是你所追求的:

    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
    
  • 5

    JavaScript的 Object is 本身就像一本字典 . 无需重新发明轮子 .

    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
    }
    

    Fiddle

  • 397
    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
    

    基本上,您正在创建一个具有2个属性(称为 keyvalue )的对象文字,并将其插入(使用 push() )到数组中 .


    Edit: 所以差不多5年之后,这个答案正在下降,因为它没有创建一个"normal" JS对象文字(又名 Map ,又名哈希,又名字典) .
    然而,它创建了OP要求的结构(并且在链接到的另一个问题中说明了),这是一个对象文字数组,每个都有 keyvalue 属性 . 唐't ask me why that structure was required, but it'是被要求的那个 .

    但是,但是,如果你想要一个简单的JS对象 - 而不是OP要求的结构 - 请参阅tcll's answer,尽管如果你只有简单的密钥是有效的JS名称,括号表示法有点麻烦 . 你可以这样做:

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

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

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

    如果您的键是动态的,您还需要括号表示法:

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

    请注意,键(属性名称)始终是字符串,非字符串值在用作键时将被强制转换为字符串 . 例如 . Date 对象转换为其字符串表示形式:

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

    但请注意,这不一定是"just work",因为许多对象将具有像 "[object Object]" 这样的字符串表示形式,这不会产生非唯一键 . 所以要警惕:

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

    尽管 objAobjB 是完全不同且独特的元素,但它们都具有相同的基本字符串表示形式: "[object Object]" .

    Date 的行为不是这样的原因是 Date 原型有一个自定义的 toString 方法,它覆盖了默认的字符串表示形式 . 你也可以这样做:

    // 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 实现(如果有),或使用默认字符串表示 .

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

    像python一样工作:)

    控制台输出:

    Object {key: "testing"}
    
  • 50

    我碰巧在这个问题上寻找类似的东西 . 它给了我足够的信息来运行测试以获得我想要的答案 . 因此,如果其他人想知道如何在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' }
    
  • 8
    var dictionary = {};//create new object
    dictionary["key1"] = value1;//set key1
    var key1 = dictionary["key1"];//get key1
    
  • 1

    您可以将 Map 与Map一起使用,如下所示:

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

    您可以创建一个类Dictionary,以便您可以轻松地与Dictionary列表进行交互:

    class Dictionary {
      constructor() {
        this.items = {};
      }
      has(key) {
        return key in this.items;
      }
      set(key,value) {
        this.items[key] = value;
      }
      delete(key) {
        if( this.has(key) ){
          delete this.items[key]
          return true;
        }
        return false;
      }
    }
    
    var d = new Dictionary();
    d.set(1, "value1")
    d.set(2, "value2")
    d.set(3, "value3")
    console.log(d.has(2));
    d.delete(2);
    console.log(d.has(2));
    
  • 0

    我遇到了这个问题..但在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];
    
  • 3

    如何创建一个键值对的衬垫怎么样?

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

    reduce 这样的迭代器函数可以动态地将数组转换为字典

    var options = [
      { key: "foo", value: 1 },
      { key: "bar", value: {id: 2, name: "two"} },
      { key: "baz", value: {["active"]: true} },
    ];
    
    var result = options.reduce((accumulator, current) => {
      accumulator[current.key] = current.value;
      return accumulator;
    }, {});
    
    console.log(result);
    
  • 18

    知道你最终想要的结果会有多大帮助,但我认为这就是你想要的:

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

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

    这将创建一个空对象 not 具有 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 :)")
    }
    

相关问题