websterz websterz - 1 year ago 85
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.

Answer Source

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



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download