Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically name a JSON property

I've been trying to create a dynamically named JSON property but I keep hitting on errors. Honestly I don't know if this is possible to achieve with Javascript. Anyway here is my problem.

Let's suppose I'm creating a JSON object like the following code:

var DTO = { 'NewObject' : GetFormData() };   var DTO = { 'UpdateObject' : GetFormData() };   var DTO = { 'DelObject' : GetFormData() };   

Now what I've been trying to do is to dynamically name the JSON property because with something like 'New' + ClassName (ClassName being a var with a string value) but it gives me a syntax error. Is there a way to do this to become something like:

var DTO = { 'New' + ClassName : GetFormData() };   var DTO = { 'Update' + ClassName : GetFormData() };   var DTO = { 'Delete' + ClassName : GetFormData() };   

I really appreciate your help. Thanks.

like image 970
Helton Valentini Avatar asked Feb 23 '10 13:02

Helton Valentini


People also ask

How to change JSON property name dynamically in JavaScript?

var DTO = { 'New' + ClassName : GetFormData() }; var DTO = { 'Update' + ClassName : GetFormData() }; var DTO = { 'Delete' + ClassName : GetFormData() };

Can JSON be dynamic?

A dynamic JSON file will be created to store the array of JSON objects. Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails. json by converting them into an array of JSON objects.

What is Property name in JSON?

Objects are the mapping type in JSON. They map “keys” to “values”. In JSON, the “keys” must always be strings. Each of these pairs is conventionally referred to as a “property”.

How do I access a JSON object?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.


2 Answers

Would this suit your needs ?

var DTO = {}; DTO['New' + ClassName] = GetFormData(); 
like image 76
instanceof me Avatar answered Oct 19 '22 19:10

instanceof me


With ECMAScript 6, you can use computed property names in object property definitions.

For example, you can simply write:

var DTO = { ['New' + ClassName] : GetFormData() }; 

More information: http://es6-features.org/#ComputedPropertyNames

like image 44
Dylan Hogg Avatar answered Oct 19 '22 20:10

Dylan Hogg