Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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.

share|improve this question
    
You cannot take a property such as Provider of a JSON string; you must first convert the string into a JavaScript object with JSON.parse() (or specify it as a JavaScript object literal to start with). – torazaburo Aug 20 at 9:46
up vote 2 down vote accepted

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

share|improve this answer
    
I am about to answer this one. Haha. Great job sir. Cheers! – Hayley Kiara Aug 20 at 8:28
    
if you're going to introduce the [keyname]: value syntax, you should at least give the proper name for this construct. Also, to be precise, this syntax does not "return" the value; it uses the value as the key name. Finally, you omitted any mention of the OP's issue with trying to manipulate a JSON string without converting it into a JavaScript object first. – torazaburo Aug 20 at 9:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.