Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 924
Jack Avatar asked Mar 02 '11 21:03

Jack


People also ask

Can you push an object into an array JavaScript?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

How do you push items into an array?

JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.

Can we push function in array?

push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.

How do you push an element to an array at first position?

The unshift() method adds new elements to the beginning of an array.


1 Answers

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.

like image 178
Lightness Races in Orbit Avatar answered Sep 26 '22 00:09

Lightness Races in Orbit