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

后端 未结 15 674
没有蜡笔的小新
没有蜡笔的小新 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:20
    var dictionary = {};//create new object
    dictionary["key1"] = value1;//set key1
    var key1 = dictionary["key1"];//get key1
    
    0 讨论(0)
  • 2020-11-28 01:20

    In ES6 you can do this:

    let cake = '                                                                    
    0 讨论(0)
  • 2020-11-28 01:24

    I happened to walk across this question looking for something similar. It gave me enough info to run a test to get the answer I wanted. So if anyone else wants to know how to dynamically add to or lookup a {key: 'value'} pair in a JavaScript object, this test should tell you all you might need to know.

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

    output

    initialValue
    { initialkey: 'initialValue',
      something: 'value1',
      somethingElse: 'value2' }
    
    0 讨论(0)
  • 2020-11-28 01:24

    how about the one liner for creating a key value pair?

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

    and some iterator function like reduce to dynamically convert an array to a dictionary

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

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

    You could create a class Dictionary so you can interact with the Dictionary list easily:

    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 讨论(0)
  • 2020-11-28 01:26

    You can use maps with Map, like this:

    var sayings = new Map();
    sayings.set('dog', 'woof');
    sayings.set('cat', 'meow');
    
    0 讨论(0)
提交回复
热议问题