In JavaScript, you can add elements to a JSON array in several ways. Here are some common methods :
Using push method
The push()
method in JavaScript is a built-in array method used to add one or more elements to the end of an array. It modifies the original array and returns the new length of the array after the elements have been added.
let jsonArray = [{name: "Ben"}, {name: "Mick"}];
// Adding a new element
jsonArray.push({name: "Cal"});
console.log(jsonArray);
Output
(3) [{...}, {...}, {...}]
0 : (1) {name: "Ben"}
1 : (1) {name: "Mick"}
2 : (1) {name: "Cal"}
[[Prototype]] : []
In this example, we have used the push()
method to add elements to the end of the array.
Using unshift method
The unshift()
method in JavaScript is used to add one or more elements to the beginning of an array. When applied, it shifts all existing elements in the array to the right, making space for the new elements at the start.
let jsonArray = [{name: "Ben"}, {name: "Mick"}];
// Adding a new element
jsonArray.unshift({name: "cal"});
console.log(jsonArray);
Output
(3) [{...}, {...}, {...}]
0 : (1) {name: "Cal"}
1 : (1) {name: "Ben"}
2 : (1) {name: "Mick"}
[[Prototype]] : []
In the above example, we have used the unshift()
method to add elements to the beginning of the array.
Using splice method
The splice()
method in JavaScript is a versatile array method that allows you to modify an array by adding or removing elements at a specific position. It can be used to insert elements, remove elements, or both in a single operation.
let jsonArray = [{name: "Ben"}, {name: "Cal"}];
// Adding a new element at index 1
jsonArray.splice(1, 0, {name: "Mick"});
console.log(jsonArray);
Output
(3) [{...}, {...}, {...}]
0 : (1) {name: "Ben"}
1 : (1) {name: "Mick"}
2 : (1) {name: "Cal"}
[[Prototype]] : []
In this example, we have used the splice()
method to insert elements at a specific position in the array.
Using spread operator
The spread operator (...
) in JavaScript is a syntax that allows you to expand elements from an iterable (like an array) into another array or function. It can be useful for creating a new array that includes existing elements along with additional ones.
let jsonArray = [{name: "Cal"}, {name: "Mick"}];
// Adding a new element
jsonArray = [...jsonArray, {name: "Ben"}];
console.log(jsonArray);
Output
(3) [{...}, {...}, {...}]
0 : (1) {name: "Cal"}
1 : (1) {name: "Mick"}
2 : (1) {name: "Ben"}
[[Prototype]] : []
In this example, we have used the spread operator (...
) to create a new array with the added elements.