34

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.

5 Answers 5

44

Would this suit your needs ?

var DTO = {}; DTO['New' + ClassName] = GetFormData();
Sign up to request clarification or add additional context in comments.

Comments

22

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

Comments

12

This is just "an object". JSON is a serialization to a string, not an object type.

If you want to use a variable as a property name, then you must create an object first, then assign the data using square bracket notation.

var foo = {};
var bar = 'baz';
foo[bar] = '123';
alert(foo.baz);

Comments

3
var DTO = Object();
DTO['New' + ClassName] = GetFormData();

Comments

0

If someone needs to keep previous data too, then use the below code:

var DTO = {}; 
DTO = {...DTO,['New' + ClassName] = GetFormData()}
DTO = {...DTO,['Update' + ClassName] = GetFormData()}

Final DTO will store both the New & Update fields.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.