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.
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.
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.
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.
The unshift() method adds new elements to the beginning of an array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With