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 Answer 1
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);
answered Aug 20, 2016 at 8:26
Suren Srapyan
68.9k14 gold badges128 silver badges119 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
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.Explore related questions
See similar questions with these tags.
lang-js
Providerof a JSON string; you must first convert the string into a JavaScript object withJSON.parse()(or specify it as a JavaScript object literal to start with).