[英]Dynamically add object in javascript array
I have json: 我有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. 但这会将pName添加为变量名,而不是Tester的变量值,我尝试使用+ pName +也不能工作。
Returns: 返回值:
{"Form":[],"Provider":[{"pName":["Testing"]}]}
Any help would be appreciated. 任何帮助,将不胜感激。
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'
. 参见示例。此处
data's
属性名为'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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.