Jack Jack - 5 months ago 31
JSON Question

JavaScript push to array

How do I push new values to the following array?

json = {"cool":"34.33","alsocool":"45454"}


I tried
json.push("coolness":"34.33");
, but it didn't work.

Answer

It's not an array.

var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;

or

var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;

you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)

var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});

Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.

Comments