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.
var DTO = { 'New' + ClassName : GetFormData() }; var DTO = { 'Update' + ClassName : GetFormData() }; var DTO = { 'Delete' + ClassName : GetFormData() };
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.
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”.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
Would this suit your needs ?
var DTO = {}; DTO['New' + ClassName] = GetFormData();
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
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