简体   繁体   English

以另一个对象的属性为键的对象

[英]Object with another's object's property as a key

I have an object like this: var myObj = {action1:0, action2:1, action3:2}; 我有一个这样的对象: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 所以在函数内部,我只能看到像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? 如何重新编写此代码以获得可读的描述?

In ES5 and earlier, you have to create that object with a series of statements: 在ES5和更早版本中,您必须使用一系列语句来创建该对象:

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: 从ES2015(又名“ ES6”)开始,您可以使用对象初始化程序中的计算属性名称来代替它:

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 . 如果稍后myObj.action1更改为42,则完成上述操作后,它对dictObj的属性名称没有任何影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM