create object using variables for property name [duplicate]

岁酱吖の 提交于 2019-11-26 04:39:24

问题


This question already has an answer here:

  • How to use a variable for a key in a JavaScript object literal? 12 answers

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

回答1:


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.




回答2:


ES6 introduces computed property names, which allow you to do

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

Note browser support is currently negligible.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/3153969/create-object-using-variables-for-property-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!