Add an Object to the End of an Array of Objects in JavaScript
How do you add an object to the end of an array of objects in JavaScript?
Below are 4 different methods.
push()
The first simple way is to use the push() method:
const arrayOfObjects = [
{ value: 1 },
{ value: 2 },
];
const newObject = { value: 3 };
arrayOfObjects.push(newObject);
Using push()
adds the newObject
to the end of the original arrayOfObjects
array. And returns the length of the new array.
arrayOfObjects
will then equal:
[
{ value: 1 }, { value: 2 }, { value: 3 },
]
Spread Syntax (...)
In ES6, the spread operator syntax was introduced.
Which allows you to do the following:
const arrayOfObjects = [
{ value: 1 },
{ value: 2 },
];
const newObject = { value: 3 };
const newArrayOfObjects = [
...arrayOfObjects,
newObject,
];
This method creates a new version of the array with the object added at the end.
Where newArrayOfObjects
equals:
[
{ value: 1 }, { value: 2 }, { value: 3 },
]
Spread Syntax with Push
This method combines push()
and the spread operator syntax:
const arrayOfObjects = [
{ value: 1 },
{ value: 2 },
];
const newObject = { value: 3 };
arrayOfObjects.push(...[newObject]);
This allows you to add the new object without creating a new array.
arrayOfObjects
would now equal:
[
{ value: 1 }, { value: 2 }, { value: 3 },
]
This method could also be used to add more than one object to the array:
arrayOfObjects.push(...[newObject1, newObject2, newObject3]);
Insert at Ending Index Position
You can also create a new index position at the end of the array and assign the new object to it:
const arrayOfObjects = [
{ value: 1 },
{ value: 2 },
];
const newObject = { value: 3 };
arrayOfObjects[arrayOfObjects.length] = newObject;
arrayOfObjects[arrayOfObjects.length]
creates a new [2]
index position in the array. And then assigns the newObject
to that position.
arrayOfObjects
would now equal:
[
{ value: 1 }, { value: 2 }, { value: 3 },
]
Thanks for reading and happy coding!