以另一个对象的属性为键的对象 [英] Object with another's object's property as a key

查看:48
本文介绍了以另一个对象的属性为键的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的对象:var myObj = {action1:0,action2:1,action3:2};

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
}  

所以在函数内部,我只能看到像0 1 2这样的值

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?

推荐答案

在ES5和更低版本中,您必须使用一系列语句来创建该对象:

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";

从ES2015(也称为"ES6")开始,您可以使用对象初始化程序中的计算属性名称来代替它:

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.

在两种情况下,请注意,没有 live 关系;如果将 myObj.action1 更改为42 以后,则完成上述操作后,它对 dictObj 中的属性名称没有任何影响.

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.

这篇关于以另一个对象的属性为键的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆