1

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.net 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);

3 Answers 3

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 
});
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

@Hugolpz, just remember, there is no such thing a JSON object, there is a JSON string that can be converted to an object or the other way around.
2

Just use

json.push({'myKey':Id, 'status':1});

You don't want a string with the variables name, but use the variable?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.