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

后端 未结 15 736
没有蜡笔的小新
没有蜡笔的小新 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: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' }
    

提交回复
热议问题