websterz websterz - 9 months ago 51
JSON Question

Dynamically add object in javascript array

I have json:

var obj = '{"Form":[],"Provider":[]}';

I push the data with variable value to make dynamic objects:

var pName = 'Tester';
var data = {
pName :["testing"]

But that adds pName as variable name but not variable value that is Tester, i tried with +pName+ that also not works.



Any help would be appreciated.


You must use [] syntax near the property name.It will evaluate the expression in the [] and returns the value.

See the example.Here the data's property is with the name 'Tester'.

var obj = {"Form":[],"Provider":[]};

var pName = 'Tester';
var data = {
    [pName] :["testing"]

console.log(data.pName); // undefined
console.log(data.Tester); // OK