Add new object to array javascript
A simple one!
In JavaScript, you can add a new object to an array using the following methods:
-
Using the
push()
method:const myArray = []; myArray.push({ name: 'John', age: 30 }); console.log(myArray); // Output: [{ name: 'John', age: 30 }]
The
push()
method adds the new object to the end of the array. -
Using the
concat()
method:const myArray = []; myArray = myArray.concat([{ name: 'John', age: 30 }]); console.log(myArray); // Output: [{ name: 'John', age: 30 }]
The
concat()
method returns a new array with the new object added to the end of the original array. -
Using the
splice()
method:const myArray = []; myArray.splice(myArray.length, 0, { name: 'John', age: 30 }); console.log(myArray); // Output: [{ name: 'John', age: 30 }]
The
splice()
method inserts the new object at the specified index (in this case, the end of the array). -
Using the
unshift()
method:const myArray = []; myArray.unshift({ name: 'John', age: 30 }); console.log(myArray); // Output: [{ name: 'John', age: 30 }]
The
unshift()
method adds the new object to the beginning of the array.
All of these methods will add a new object to the array. Choose the one that best fits your use case!