-4

This is my JSON with Javascript:

/**
 * @param {String} value1
 * @param {String} value2
 * @param {String} value3
 * @param {Number} value4
 * 
 * @constructor 
 * @properties={typeid:24,uuid:"F146465E-7D8C-4D8B-B37C-954E65AFBEAD"}
 */
function CarData (value1, value2, value3, value4)
{
    this.car = {
        field1: value1,
        field2: value2,
        field3: value3,
        field4: value4
    }
}

I want to do that the fieldXbe dynamic like the value passed with parameters.

Is that possible?

Then I will transform that object to JSON with:

JSON.stringify(object);
user1911
  • 680
  • 1
  • 14
  • 36
  • 1
    The question isn't clear. What do you need help with? – Bhargav Ponnapalli Jan 30 '16 at 09:12
  • Possible duplicate of [How do I add a property to a Javascript Object using a variable as the name?](http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – JJJ Jan 30 '16 at 09:14
  • 1
    Or a duplicate of [How can I add a key/value pair to a JavaScript object?](http://stackoverflow.com/q/1168807/218196) ... either way, the question was very likely asked before. – Felix Kling Jan 30 '16 at 09:15

1 Answers1

2

Yes, you can assign dynamic field values using the [] operator.

Example:

this.car = {}; // this just creates an empty object
this.car['typeid'] = 24; // same as this.car.typeid = ..
for(var i = 0; i < 4; i++) {
  this.car['part' + i] = parts[i]; // assign to dynamic fieldname 'partX'
}
ZeissS
  • 11,867
  • 4
  • 35
  • 50