websterz websterz - 3 months ago 10
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"]
};
console.log(obj['Provider'].push(data));


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

Returns:

{"Form":[],"Provider":[{"pName":["Testing"]}]}


Any help would be appreciated.

Answer

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

obj['Provider'].push(data);

console.log(obj);

Comments