admin管理员组文章数量:1410724
Given the following data:
var json = [
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 1 },
{ 'myKey': 'C', 'status': 1 },
{ 'myKey': 'D', 'status': 1 }
];
I want to append a new array with a variable "Id", something like :
var Id = "aNewLetterFunction";
json.push({'myKey':'+Id+','status':1}); //this doesn't work
How can I do, since the +Id+ is not natively considered as a variable ? JSfiddle appreciate.
EDIT: fiddle available
I tried various things such :
json.push('{"myKey":"'+Id+'","status":1},');
or
var ar1 = '{"myKey":"';
var Id = Id;
var ar2 = '","status":1},';
json.push(ar1+Id+ar2);
Given the following data:
var json = [
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 1 },
{ 'myKey': 'C', 'status': 1 },
{ 'myKey': 'D', 'status': 1 }
];
I want to append a new array with a variable "Id", something like :
var Id = "aNewLetterFunction";
json.push({'myKey':'+Id+','status':1}); //this doesn't work
How can I do, since the +Id+ is not natively considered as a variable ? JSfiddle appreciate.
EDIT: fiddle available
I tried various things such :
json.push('{"myKey":"'+Id+'","status":1},');
or
var ar1 = '{"myKey":"';
var Id = Id;
var ar2 = '","status":1},';
json.push(ar1+Id+ar2);
Share
Improve this question
edited Feb 12, 2013 at 21:06
Hugolpz
asked Feb 12, 2013 at 19:46
HugolpzHugolpz
18.3k28 gold badges105 silver badges191 bronze badges
3 Answers
Reset to default 3json
is probably not a good variable name since you have an array of objects, and JSON is, by definition, a string.
That note aside, you would just construct an object literal and push that:
var Id = "aNewLetterFunction";
json.push({
myKey: Id,
status: 1
});
Create an object, don't create a JSON string:
json.push({
myKey:Id,
status:'1'
});
You don't want to add another value to the JSON but to the array that can be parsed to a JSON string, but isn't a string.
Live DEMO
Just use
json.push({'myKey':Id, 'status':1});
You don't want a string with the variables name, but use the variable?
本文标签: javascriptJS How to append array with variable into JSONStack Overflow
版权声明:本文标题:javascript - JS: How to append array with variable into JSON? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744801340a2625877.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论