Object with another's object's property as a key

后端 未结 1 1928
天命终不由人
天命终不由人 2020-12-12 06:50

I have an object like this: var myObj = {action1:0, action2:1, action3:2};

Test function gets values from this list as parameters and to simplify unit-testing I want

相关标签:
1条回答
  • 2020-12-12 07:25

    In ES5 and earlier, you have to create that object with a series of statements:

    var dictObj = {};
    dictObj[myObj.action1] = "action1";
    dictObj[myObj.action2] = "action2";
    dictObj[myObj.action3] = "action3";
    

    As of ES2015 (aka "ES6"), you can do it with computed property names in the object initializer instead:

    let dictObj = {
        [myObj.action1]: "action1",
        [myObj.action2]: "action2",
        [myObj.action3]: "action3"
    };
    

    You can use any expression within the [] to create the property name; in this case it's just a simple property lookup.

    In both cases, note that there's no live relationship; if you change myObj.action1 to 42 later, after doing the above, it doesn't have any effect on the property name in dictObj.

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