How to create dictionary and add key–value pairs dynamically?

后端 未结 15 673
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 00:37

From post:

Sending a JSON array to be received as a Dictionary

I’m trying to do this same thing as that post. The only issue is that I d

相关标签:
15条回答
  • 2020-11-28 01:28

    An improvement on var dict = {} is to use var dict = Object.create(null).

    This will create an empty object that does not have Object.prototype as it's 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 :)")
    }
    
    0 讨论(0)
  • 2020-11-28 01:30

    JavaScript's Object is in itself like a dictionary. No need to reinvent the wheel.

    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

    0 讨论(0)
  • 2020-11-28 01:31

    In modern javascript (ES6/ES2015), one should use Map data structure for dictionary. The Map data structure in ES6 lets you use arbitrary values as keys.

    const map = new Map();
    map.set("true", 1);
    map.set("false", 0);
    

    In you are still using ES5, the correct way to create dictionary is to create object without a prototype in the following way.

    var map = Object.create(null);
    map["true"]= 1;
    map["false"]= 0;
    

    There are many advantages of creating a dictionary without a prototype object. Below blogs are worth reading on this topic.

    dict-pattern

    objects-as-maps

    0 讨论(0)
提交回复
热议问题