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
Add a ment  | 

3 Answers 3

Reset to default 3

json 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