Javascript 使用属性名称的变量创建对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3153969/
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-08-23 03:28:31  来源:igfitidea点击:

create object using variables for property name

javascriptpropertiesobject-literal

提问by balafi

Is it at all possible to use variable names in object literal properties for object creation?

是否可以在对象文字属性中使用变量名来创建对象?

Example

例子

function createJSON (propertyName){
    return { propertyName : "Value"};
}

var myObject = createJSON("myProperty");

console.log(myObject.propertyName);  // Prints "value"
console.log(myObject.myProperty);  // This property does not exist

回答by Quentin

If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets:

如果要为属性名称使用变量,可以使用Computed Property Names。将变量名放在方括号之间:

var foo = "bar";
var ob  = { [foo]: "something" }; // ob.bar === "something"

If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel):

如果您想要 Internet Explorer 支持,您将需要使用 ES5 方法(您可以通过编写现代语法(如上)然后应用Babel 来获得):

Create the object first, and then add the property using square bracket notation.

首先创建对象,然后使用方括号表示法添加属性。

var foo = "bar";
var ob  = {};
ob[foo] = "something"; // === ob.bar = "something"

If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringifymethod.

如果您想以编程方式创建 JSON,则必须将对象序列化为符合 JSON 格式的字符串。例如,用JSON.stringify方法

回答by Oriol

ES6 introduces computed property names, which allow you to do

ES6 引入了计算属性名称,它允许你做

function CreateJSON (propertyName){
    var myObject = { [propertyName] : "Value"};
}

Note browser support is currently negligible.

注意浏览器支持目前可以忽略不计。

回答by Mark Schultheiss

You can sort of do this:

你可以这样做:

  var myObject = {};
  CreateProp("myProperty","MyValue");

  function CreateProp(propertyName, propertyValue)
  {
      myObject[propertyName] = propertyValue;
      alert(myObject[propertyName]);  // prints "MyValue" 
  };

I much perfer this syntax myself though:

不过,我自己更喜欢这种语法:

function jsonObject()
{
};
var myNoteObject = new jsonObject();

function SaveJsonObject()
{
    myNoteObject.Control = new jsonObject();
    myNoteObject.Control.Field1= "Fred";
    myNoteObject.Control.Field2= "Wilma";
    myNoteObject.Control.Field3= "Flintstone";
    myNoteObject.Control.Id= "1234";
    myNoteObject.Other= new jsonObject();
    myNoteObject.Other.One="myone";
};

Then you can use the following:

然后您可以使用以下内容:

SaveJsonObject();
var myNoteJSON = JSON.stringify(myNoteObject);

NOTE: This makes use of the json2.js from here:http://www.json.org/js.html

注意:这里使用了 json2.js:http: //www.json.org/js.html

回答by Chase

One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.

可能适合的一件事(现在 JSON 功能对于较新的浏览器很常见,并且 json2.js 是一个完全有效的后备),是构造一个 JSON 字符串然后解析它。

function func(prop, val) {
    var jsonStr = '{"'+prop+'":'+val+'}';
    return JSON.parse(jsonStr);
}

var testa = func("init", 1);
console.log(testa.init);//1

Just keep in mind, JSON property names need to be enclosed in double quotes.

请记住,JSON 属性名称需要用双引号括起来。