Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  27] [ 2]  / answers: 1 / hits: 108135  / 14 Years ago, wed, june 30, 2010, 12:00:00

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

More From » properties

 Answers
41

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.


[#96370] Sunday, June 27, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makaylahk

Total Points: 166
Total Questions: 94
Total Answers: 117

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;