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

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

例子

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
105839 次浏览

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

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):

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.stringify method.

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

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.

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.

ES6 introduces computed property names, which allow you to do

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

Note browser support is currently negligible.