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
You cannot. Property keys are unique.
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.
ES6 introduces computed property names, which allow you to do
function CreateJSON (propertyName){ var myObject = { [propertyName] : "Value"}; }
Note browser support is currently negligible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With