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

前端 未结 5 1786
-上瘾入骨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条回答
  •  闹比i
    闹比i (楼主)
    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}
    

提交回复
热议问题