Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

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

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 to get human readable labels inside of the function

function myFunc(someaction, anotheraction, blablabla)
{
    console.log("Action: " + arguments[0] + " then action: " + arguments[1]);
    //some code here
}  

So inside of the function I can see only values like 0 1 2

Trying to workaround I tried to create new object like this

var dictObj = {myObj.action1:"action1", myObj.action2:"action2", myObj.action3:"action3"}

and then resolve values to names inside of the function:

console.log("Action: " + dictObj[arguments[0]] + " then action: " + dictObj[arguments[1]]);

But it didn't work because of

'Uncaught SyntaxError: Unexpected token .'

How I can rework this code to get readable description?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...