JavaScript provides several ways to add an object to an array. The most commonly used method is the push()
method, which adds an element to the end of an array. Here is an example of how to use the push()
method:
let fruits = ['apple', 'banana', 'orange'];
let newFruit = { name: 'mango', color: 'yellow' };
fruits.push(newFruit);
console.log(fruits); // Output: ['apple', 'banana', 'orange', { name: 'mango', color: 'yellow' }]
In this example, the push()
method is used to add the newFruit
object to the end of the fruits array. The console.log()
statement is used to display the updated array, which now includes the newFruit
object.
Another way to add an object to an array is to use the concat()
method. This method combines two arrays and returns a new array that contains the elements of both arrays. Here is an example of how to use the concat()
method:
let fruits = ['apple', 'banana', 'orange'];
let newFruit = { name: 'mango', color: 'yellow' };
let updatedFruits = fruits.concat(newFruit);
console.log(updatedFruits); // Output: ['apple', 'banana', 'orange', { name: 'mango', color: 'yellow' }]
In this example, the concat()
method is used to combine the fruits
array and the newFruit
object into a new array called updatedFruits
. The console.log()
statement is used to display the updated array, which now includes the newFruit
object.
Another way to add an object to an array is to use the spread operator.
let fruits = ['apple', 'banana', 'orange'];
let newFruit = { name: 'mango', color: 'yellow' };
fruits = [...fruits, newFruit];
console.log(fruits); // Output: ['apple', 'banana', 'orange', { name: 'mango', color: 'yellow' }]
In this example, the spread operator is used to add the newFruit object to the fruits array. The console.log()
statement is used to display the updated array, which now includes the newFruit
object.
Lastly, you can use the square bracket notation to add a new element to an array.
let fruits = ['apple', 'banana', 'orange'];
let newFruit = { name: 'mango', color: 'yellow' };
fruits[fruits.length] = newFruit;
console.log(fruits); // Output: ['apple', 'banana', 'orange', { name: 'mango', color: 'yellow' }]
In this example, the newFruit
object is added to the fruits
array by using the square bracket notation and the length
property of the fruits
array. The console.log()
statement is used to display the updated array, which now includes the newFruit
object.