How do I push new values to the following javascript array?
json = {"cool":"34.33","alsocool":"45454"}
I tried
json.push("coolness":"34.33");
but it didnt work
How do I push new values to the following javascript array?
json = {"cool":"34.33","alsocool":"45454"}
I tried
json.push("coolness":"34.33");
but it didnt work
accidentally tried to use an array method on a plain object. As already notes, your value is an object, not an array; ’s suggestions are on the right track. Push only works on arrays — to add a property to an object set a key, or merge objects with native helpers.
Simple options (native):
let data = {a: "34.33", b: "45454"};
// add or overwrite one property
data["coolness"] = "34.33"; let merged = Object.assign({}, data, {coolness: "34.33"});
// or with modern syntax
let copy = {...data, coolness: "34.33"}; If your starting value is a JSON string, parse it first, adjust the object, then stringify if you need a string.
Troubleshooting and tips
push: use Array.isArray(x) (because typeof returns "object" for arrays). const/let over var, and avoid naming variables json (it’s confusing — JSON is the format). Object.assign) instead of mutating the original. Number()/parseFloat()) instead of leaving them as strings.If you intended an array of items, convert or create an array and then use push to append elements (e.g., arr.push({coolness: 34.33})). Otherwise, add properties to the object as shown above.
Jump to Post— lambing 0you could jQuery's extend method.
var obj1 = {"cool":"34.33","alsocool":"45454"}; var obj2 = {"coolness":"34.33"}; $.extend(obj1, obj2);The value of the first object will contain obj2.
console.log(obj1);The above statement will log something like this:
{"cool":"34.33","alsocool":"45454", "coolness":"34.33"}If you don't …
you could jQuery's extend method.
var obj1 = {"cool":"34.33","alsocool":"45454"};
var obj2 = {"coolness":"34.33"};
$.extend(obj1, obj2);
The value of the first object will contain obj2.
console.log(obj1);
The above statement will log something like this:
{"cool":"34.33","alsocool":"45454", "coolness":"34.33"}
If you don't want to use jQuery, you can try the native and easy way by doing this:
json.coolness = "34.33";
Everything in JavaScript is an object, you can assign properties to objects easily and set it's value
Sir Saula,
{"cool":"34.33","alsocool":"45454"} is a plain javascript object not an array.
Add extra properties as per Lambing's suggestions.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.