JavaScript push to array

Jack picture Jack · Mar 2, 2011 · Viewed 205k times · Source

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

Lightness Races in Orbit picture Lightness Races in Orbit · Mar 2, 2011

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.