给定以下数据:
var json = [
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 1 },
{ 'myKey': 'C', 'status': 1 },
{ 'myKey': 'D', 'status': 1 }
];
我想附加一个带有变量“Id”的新数组,类似于:
var Id = "aNewLetterFunction";
json.push({'myKey':'+Id+','status':1}); //this doesn't work
我该怎么做,因为 +Id+ 本身不被视为变量? JSfiddle.net 感谢。
编辑: fiddle available
我尝试了很多事情,例如:
json.push('{"myKey":"'+Id+'","status":1},');
或
var ar1 = '{"myKey":"';
var Id = Id;
var ar2 = '","status":1},';
json.push(ar1+Id+ar2);
最佳答案
json
可能不是一个好的变量名,因为您有一个对象数组,而根据定义,JSON 是一个字符串。
撇开这一点不谈,您只需构造一个对象字面量并将其推送:
var Id = "aNewLetterFunction";
json.push({
myKey: Id,
status: 1
});
关于javascript - JS : How to append array with variable into JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840510/