javascript 创建具有动态属性名称的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17832583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:48:09  来源:igfitidea点击:

Create an object with dynamic property names

javascript

提问by blueFast

I am trying to do this:

我正在尝试这样做:

var KEYS = {} ;

KEYS.PHONE_TYPE = 'phone-type';
KEYS.AGENT_TYPE = 'agent-type';

var myAppConfig = {
    ...
    iconMap : { 
        KEYS.PHONE_TYPE : 'icon-phone', 
        KEYS.AGENT_TYPE : 'icon-headphones'
    };
    ...
};

But it is failing, with a message: Expected ':' and instead saw '.'.

但它失败了,并显示一条消息: Expected ':' and instead saw '.'.

How can I initialize an object using indirect (non-literal) keynames?

如何使用间接(非文字)键名初始化对象?

To be clear, the result I want is:

要清楚,我想要的结果是:

{
    'phone-type' : 'icon-phone',
    'agent-type' : 'icon-headphones'
}

回答by Dragos Bobolea

If you're using ES6 (or something like Babel/browserify), you can write it like this:

如果你使用 ES6(或类似 Babel/browserify),你可以这样写:

iconMap : { 
    [KEYS.PHONE_TYPE] : 'icon-phone', 
    [KEYS.AGENT_TYPE] : 'icon-headphones'
};

回答by Sirko

You would have to add those properties separately using bracket notation:

您必须使用括号表示法单独添加这些属性:

var myAppConfig = {
    ...
    iconMap : { }
    ...
};

myAppConfig.iconMap[ KEYS.PHONE_TYPE ] = 'icon-phone';
myAppConfig.iconMap[ KEYS.AGENT_TYPE ] = 'icon-headphones';