简体   繁体   English

将对象文字传递给函数内具有变量名称的对象

[英]Pass an object literal to an object with a variable name inside a function

This is just an example: 这只是一个例子:

var foo = "foo1";
fooFunction({
    bar: {
        foo : value
    }
});

The property will be named foo instead of foo1 . 该属性将命名为foo而不是foo1

How can I make it be called foo1 ? 如何将其称为foo1

You cannot specify a dynamic property name in an object literal, you would have to add the property after the object is created. 您不能在对象文字中指定动态属性名称,必须在创建对象后添加属性。

var foo = "foo1";
var obj = {
    bar: {}
};
obj.bar[foo] = value;
function(obj);

There's nothing special about an object literal when used as an input to a function call. 当对象常量用作函数调用的输入时,没有什么特别的。 The rules of object literals apply wherever it is used, including assignment, input parameters, destructing (ES2015) or any other usage I might have left out. 对象文字的规则适用于任何地方,包括赋值,输入参数,销毁(ES2015)或我可能遗漏的任何其他用法。

It is possible using ES2015 to do this with a slight change: 可以使用ES2015稍作更改即可做到这一点:

var foo = "foo1";
fooFunction({
    bar: {
        [foo] : value
    }
});

This is called computed property name. 这称为计算属性名称。

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

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