Awais Zaib
Awais Zaib

Reputation: 45

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.

Upvotes: 3

Views: 4668

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68635

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);

Upvotes: 5

Related Questions