- Array.prototype.push()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Adding elements to an array
- Merging two arrays
- Calling push() on non-array objects
- Using an object in an array-like fashion
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Javascript push to array of objects
- # Table of Contents
- # Push an Object to an Array in JavaScript
- # Adding the object to the array upon declaration
- # Pushing multiple objects to an array with Array.push()
- # Pushing an object to the beginning of an array with unshift()
- # Pushing multiple objects to the beginning of an array
- # Push an Object into an Array using spread syntax
- # Pushing an Object to an Array using Array.splice()
- # Pushing an object to an array using Array.concat
- # Additional Resources
- How to Push an Object to an Array in JavaScript
- Push object to array during initialization
- Push multiple objects to array
- Push object to array without mutation
- Every Crazy Thing JavaScript Does
Array.prototype.push()
The push() method adds the specified elements to the end of an array and returns the new length of the array.
Try it
Syntax
push() push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN)
Parameters
The element(s) to add to the end of the array.
Return value
The new length property of the object upon which the method was called.
Description
The push() method appends values to an array.
Array.prototype.unshift() has similar behavior to push() , but applied to the start of an array.
The push() method is a mutating method. It changes the length and the content of this . In case you want the value of this to be the same, but return a new array with elements appended to the end, you can use arr.concat([element0, element1, /* . ,*/ elementN]) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of concat() .
The push() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
Adding elements to an array
The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.
const sports = ["soccer", "baseball"]; const total = sports.push("football", "swimming"); console.log(sports); // ['soccer', 'baseball', 'football', 'swimming'] console.log(total); // 4
Merging two arrays
This example uses spread syntax to push all elements from a second array into the first one.
const vegetables = ["parsnip", "potato"]; const moreVegs = ["celery", "beetroot"]; // Merge the second array into the first one vegetables.push(. moreVegs); console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
Merging two arrays can also be done with the concat() method.
Calling push() on non-array objects
The push() method reads the length property of this . It then sets each index of this starting at length with the arguments passed to push() . Finally, it sets the length to the previous length plus the number of pushed elements.
const arrayLike = length: 3, unrelated: "foo", 2: 4, >; Array.prototype.push.call(arrayLike, 1, 2); console.log(arrayLike); // const plainObj = >; // There's no length property, so the length is 0 Array.prototype.push.call(plainObj, 1, 2); console.log(plainObj); //
Using an object in an array-like fashion
As mentioned above, push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.
Note that we don’t create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.
const obj = length: 0, addElem(elem) // obj.length is automatically incremented // every time an element is added. [].push.call(this, elem); >, >; // Let's add some empty objects just to illustrate. obj.addElem(>); obj.addElem(>); console.log(obj.length); // 2
Note that although obj is not an array, the method push successfully incremented obj ‘s length property just like if we were dealing with an actual array.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 19, 2023 by MDN contributors.
Your blueprint for a better internet.
Javascript push to array of objects
Last updated: Feb 9, 2023
Reading time · 5 min
# Table of Contents
# Push an Object to an Array in JavaScript
Use the Array.push() method to push an object to an array, e.g. arr.push(object); .
The Array.push() method will push the supplied object to the end of the array.
Copied!const arr = []; const obj = name: 'Tom'>; arr.push(obj); console.log(arr); // 👉️ []
We used the Array.push() method to push an object to an array.
The object gets pushed to the end of the array.
If you only have the values that the object should contain, create the object before pushing it into the array.
Copied!const arr = []; const obj = >; const name = 'Tom'; obj['name'] = name; arr.push(obj); console.log(arr); // 👉️ []
Once the key-value pairs are assigned to the object, use the Array.push() method to add the object to the end of the array.
# Adding the object to the array upon declaration
If you haven’t declared the array, you can add the objects to the array when declaring the variable.
Copied!const obj1 = name: 'Tom'>; const obj2 = name: 'Alice'>; const arr = [obj1]; console.log(arr); // [ < name: 'Tom' >] const arr2 = [obj1, obj2]; console.log(arr2); // [ < name: 'Tom' >, < name: 'Alice' >]
We added the objects between the square brackets to declare an array of objects.
# Pushing multiple objects to an array with Array.push()
The same approach can be used to push multiple objects to an array.
Copied!const arr = []; const obj1 = name: 'Alice'>; const obj2 = name: 'Bob'>; const obj3 = name: 'Carl'>; arr.push(obj1, obj2, obj3); // 👇️ [, , ] console.log(arr);
We used the Array.push() method to push 3 objects to an array in a single statement.
The Array.push() method takes one or more values and pushes them to the array.
This enables us to pass multiple, comma-separated objects as arguments in the call to the push() method.
# Pushing an object to the beginning of an array with unshift()
If you want to push an object to the beginning of an array, use the Array.prototype.unshift() method.
Copied!const arr = [id: 2, name: 'Bobby'>]; const obj = id: 1, name: 'Alice'>; arr.unshift(obj); // 👇️ [ < id: 1, name: 'Alice' >, < id: 2, name: 'Bobby' >] console.log(arr);
The Array.unshift() method adds one or more elements to the beginning of an array.
# Pushing multiple objects to the beginning of an array
The Array.unshift() method can also be called with multiple objects.
Copied!const arr = [id: 3, name: 'Carl'>]; const obj1 = id: 1, name: 'Alice'>; const obj2 = id: 2, name: 'Bobby'>; arr.unshift(obj1, obj2); // [ // < id: 1, name: 'Alice' >, // < id: 2, name: 'Bobby' >, // // ] console.log(arr);
The statement adds the 2 supplied objects to the beginning of the array.
You can also use dot notation to add key-value pairs to an object. You just have to make sure the names of the keys don’t contain spaces and don’t start with special characters.
Copied!let arr = []; const obj = >; obj.name = 'Tom'; obj.age = 30; console.log(obj); // 👉️ arr.push(obj); console.log(arr); // 👉️ [ < name: 'Tom', age: 30 >]
Using dot notation to add properties to an object is much more concise and elegant.
However, make sure to use bracket notation if the name of the key contains spaces.
Alternatively, you can use the spread syntax (. ).
# Push an Object into an Array using spread syntax
This is a three-step process:
- Declare the array using the let keyword.
- Use the spread syntax (. ) to unpack the array and add the object.
- Reassign the value of the array variable to the result.
Copied!let arr = [id: 1, name: 'Alice'>]; const obj = id: 2, name: 'Bobby'>; arr = [. arr, obj]; // 👇️ [ < id: 1, name: 'Alice' >, < id: 2, name: 'Bobby' >] console.log(arr);
We used the spread syntax (. ) to unpack the elements of the array into a new array and added the object at the end.
You can imagine that the . syntax unpacks the array’s elements (objects) into a new array to which we can add additional objects.
Notice that we used the let keyword when declaring the arr variable.
This is important because variables declared using const cannot be reassigned.
You can also unpack the array after the object if you want to add the object at the beginning of the array.
Copied!let arr = [id: 1, name: 'Alice'>]; const obj = id: 2, name: 'Bobby'>; arr = [obj, . arr]; // 👇️ [ < id: 2, name: 'Bobby' >, < id: 1, name: 'Alice' >] console.log(arr);
The order in which the array elements are unpacked is preserved.
# Pushing an Object to an Array using Array.splice()
If you need to push an object into an array at a specific index, use the Array.splice() method.
The Array.splice() method takes the index at which to insert the object and the object as arguments.
Copied!const arr = [ id: 1, name: 'Alice'>, id: 3, name: 'Carl'>, ]; const obj2 = id: 2, name: 'Bobby'>; arr.splice(1, 0, obj2); // [ // < id: 1, name: 'Alice' >, // < id: 2, name: 'Bobby' >, // // ] console.log(arr);
The code sample inserts the object into the array at index 1 .
We passed the following arguments to the Array.splice method:
- The start index — the index at which to start changing the array.
- The delete count — the number of elements to be deleted from the array from the start index onwards.
- The elements to add to the array beginning from start.
We used 1 as the start index to add the object to the array at index 1 .
We specified a value of 0 for the delete count argument to not remove any elements from the array.
Lastly, we passed the object as the third argument to the Array.splice() method.
You can use the same approach to add multiple objects to the array at the specified index.
Copied!const arr = [ id: 1, name: 'Alice'>, id: 4, name: 'Dean'>, ]; const obj2 = id: 2, name: 'Bobby'>; const obj3 = id: 3, name: 'Carl'>; arr.splice(1, 0, obj2, obj3); // [ // < id: 1, name: 'Alice' >, // < id: 2, name: 'Bobby' >, // < id: 3, name: 'Carl' >, // // ] console.log(arr);
We passed multiple objects to the Array.splice() method and they all got added to the array starting at index 1 .
# Pushing an object to an array using Array.concat
You can also use the Array.concat() method to push an object to an array.
Copied!const arr = []; const obj1 = name: 'Tom'>; const obj2 = name: 'Alice'>; const arr2 = arr.concat(obj1, obj2); console.log(arr2); // 👉️ [ < name: 'Tom' >, < name: 'Alice' >]
The Array.concat() method is used to merge two or more arrays.
We called the concat() method on the first array and passed it 2 objects.
The concat() method can get called with as many comma-separated values as necessary.
The method returns a new array that is first populated by the elements in the array on which it was called.
Then, each of the supplied objects gets added to the new array.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How to Push an Object to an Array in JavaScript
To push an object to an array in JavaScript, call the push() method on the array with the object as an argument, i.e., arr.push(obj) . The push() method will add the element to the end of the array.
const arr = []; const obj = < name: 'Jeff' >; // 👇 Push object to array arr.push(obj); // [ < name: 'Jeff' >] console.log(arr);
The push() method takes an object and adds it to the end of an array.
Push object to array during initialization
If the variable is newly created just before the object is pushed (like in the previous example), you can simply place the object in between the square brackets ( [] ) to include it in the array as the variable is initialized:
const obj = < name: 'Jeff' >; // 👇 Push object to array with initialization const arr = [obj]; console.log(arr);
Push multiple objects to array
The push() method actually accepts a variable number of arguments. They are each added to the end of the array, in the order in which they are passed to push() .
const arr = []; const obj1 = < name: 'Samantha' >; const obj2 = < name: 'Chris' >; const obj3 = < name: 'Mike' >; arr.push(obj1, obj2, obj3); // [ < name: 'Samantha' >, < name: 'Chris' >, < name: 'Mike' >] console.log(arr);
Push object to array without mutation
The push() method adds an object to the array in place, which means it gets modified. If you don’t want this, you can use the spread syntax ( . ) to create a copy of the original array, before calling push() :
const arr = [< name: 'Jerry' >]; const newArr = [. arr]; newArr.push(< name: 'Mia' >); // [ < name: 'Jerry' >, < name: 'Mia' >] console.log(newArr); // 👇 Original not modified console.log(arr); // [ < name: 'Jerry' >]
Similar to what we did earlier, we can include the object in the square brackets, after the spread syntax, to push the object to the array’s copy as it is initialized:
const arr = [< name: 'Jerry' >]; // 👇 Push object to array without mutation const newArr = [. arr, < name: 'Mia' >]; // [ < name: 'Jerry' >, < name: 'Mia' >] console.log(newArr); // Original not modified console.log(arr); // [ < name: 'Jerry' >]
While not always necessary, by avoiding mutations we can make our code more readable, predictable, and modular.
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.