First Parse the JSON object to create a native JavaScript Object then Push the new array element into the object using the push() method. This way you can add to JSON Array in JavaScript.
Note: Use stringify()
to convert it back to its original format.
JavaScript add to JSON Array
Simple example code adding a new array element to a JSON object
<!DOCTYPE html>
<html>
<body>
<script>
var data = '{"characters":[{"name":"Tommy Vercetti","location":"Vice City"},{"name":"Carl Johnson","location":"Grove Street"},{"name":"Niko Bellic","location":"Liberty City"}]}'
const obj = JSON.parse(data);
obj["characters"].push({ name: "Ken Rosenberg", location: "Vice City" });
console.log(obj);
</script>
</body>
</html>
Output:
JSON is just a notation; to make the change you want to parse it so you can apply the changes to a native JavaScript Object, then stringify it back to JSON.
Simply use the push method of Arrays
var data = [
{ name: "Pawan" },
{ name: "Goku" },
{ name: "Naruto" }
];
var obj = { name: "Light" };
data.push(obj);
console.log(data);
Output:
0: Object { name: "Pawan" }
1: Object { name: "Goku" }
2: Object { name: "Naruto" }
3: Object { name: "Light" }
Do comment if you have any doubts or suggestions on this JS JSON topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version