How to fill a Javascript object literal with many static key/value pairs efficiently?

前端 未结 5 1784
-上瘾入骨i
-上瘾入骨i 2021-01-31 15:36

The typical way of creating a Javascript object is the following:

var map = new Object();
map[myKey1] = myObj1;
map[myKey2] = myObj2;

I need to

相关标签:
5条回答
  • 2021-01-31 15:56

    JavaScript's object literal syntax, which is typically used to instantiate objects (seriously, no one uses new Object or new Array), is as follows:

    var obj = {
        'key': 'value',
        'another key': 'another value',
         anUnquotedKey: 'more value!'
    };
    

    For arrays it's:

    var arr = [
        'value',
        'another value',
        'even more values'
    ];
    

    If you need objects within objects, that's fine too:

    var obj = {
        'subObject': {
            'key': 'value'
        },
        'another object': {
             'some key': 'some value',
             'another key': 'another value',
             'an array': [ 'this', 'is', 'ok', 'as', 'well' ]
        }
    }
    

    This convenient method of being able to instantiate static data is what led to the JSON data format.

    JSON is a little more picky, keys must be enclosed in double-quotes, as well as string values:

    {"foo":"bar", "keyWithIntegerValue":123}
    
    0 讨论(0)
  • 2021-01-31 16:00

    It works fine with the object literal notation:

    var map = { key : { "aaa", "rrr" }, 
                key2: { "bbb", "ppp" } // trailing comma leads to syntax error in IE!
              }
    

    Btw, the common way to instantiate arrays

    var array = [];
    // directly with values:
    var array = [ "val1", "val2", 3 /*numbers may be unquoted*/, 5, "val5" ];
    

    and objects

    var object = {};
    

    Also you can do either:

    obj.property     // this is prefered but you can also do
    obj["property"]  // this is the way to go when you have the keyname stored in a var
    
    var key = "property";
    obj[key] // is the same like obj.property
    
    0 讨论(0)
  • 2021-01-31 16:07

    Give this a try:

    var map = {"aaa": "rrr", "bbb": "ppp"};
    
    0 讨论(0)
  • 2021-01-31 16:12

    In ES2015 a.k.a ES6 version of JavaScript, a new datatype called Map is introduced.

    let map = new Map([["key1", "value1"], ["key2", "value2"]]);
    map.get("key1"); // => value1
    

    check this reference for more info.

    0 讨论(0)
  • 2021-01-31 16:14

    The syntax you wrote as first is not valid. You can achieve something using the follow:

    var map =  {"aaa": "rrr", "bbb": "ppp" /* etc */ };
    
    0 讨论(0)
提交回复
热议问题