JavaScript(JS) JS append an object to an array
In JavaScript, you can append an object to an array using the push()
method. Here's an example:
let myArray = [{ name: "John", age: 30 }, { name: "Mary", age: 25 }]; let newObject = { name: "Bob", age: 40 }; myArray.push(newObject); console.log(myArray); // Output: [{ name: "John", age: 30 }, { name: "Mary", age: 25 }, { name: "Bob", age: 40 }]
In the example above, we create an array myArray
with two objects as elements. We then create a new object newObject
with a name
property of "Bob"
and an age
property of 40
. We append the new object to the myArray
array using the push()
method. The resulting array is [{ name: "John", age: 30 }, { name: "Mary", age: 25 }, { name: "Bob", age: 40 }]
.
Note that the push()
method modifies the original array by adding the new element to the end of it. If you need to insert the new element at a specific position in the array, you can use the splice()
method instead. For example, to insert the new object at the beginning of the array, you could do:
let myArray = [{ name: "John", age: 30 }, { name: "Mary", age: 25 }]; let newObject = { name: "Bob", age: 40 }; myArray.splice(0, 0, newObject); console.log(myArray); // Output: [{ name: "Bob", age: 40 }, { name: "John", age: 30 }, { name: "Mary", age: 25 }]
In the example above, we use the splice()
method to insert the new object at position 0
of the myArray
array, which pushes all the existing elements to the right. The resulting array is [{ name: "Bob", age: 40 }, { name: "John", age: 30 }, { name: "Mary", age: 25 }]
.