3

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.

1
  • 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). Commented Aug 20, 2016 at 9:46

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

I am about to answer this one. Haha. Great job sir. Cheers!
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.