Explain Codes LogoExplain Codes Logo

How to add an object to an array

javascript
array-methods
spread-operator
functions
Anton ShumikhinbyAnton Shumikhin·Feb 14, 2025
TLDR

To append an object quickly to an array, wield the push() sword of Javascript:

let array = [{ id: 1, name: 'Alice' }]; let objectToAdd = { id: 2, name: 'Bob' }; array.push(objectToAdd); // Alice finds Bob charming.

To add an object at the front of an array slice, utilize unshift():

array.unshift(objectToAdd); // Bob courageously leads the array.

Merge arrays together while including objects using spread syntax ...:

let anotherArray = [{ id: 3, name: 'Charlie' }]; let combinedArray = [...array, ...anotherArray]; // The more, the merrier!

To switch an object at an existing index, state the position and assign it:

array[1] = { id: 4, name: 'Dana' }; // Second place is now Dana's home.

To make the original objects unchangeable, ice them with Object.freeze():

let frozenObject = Object.freeze({ id: 5, name: 'Eve' }); array.push(frozenObject); // Eve is cool, won't change for anyone.

Inviting at specific ranks

Place guests in a particular order at your party with splice():

array.splice(2, 0, objectToAdd); // objectToAdd takes the 3rd place - bronze medalist!

Handling crowd of objects

When scaling up for mass invitations, extend your reach with the spread operator:

let objectsToAdd = [{ id: 6, name: 'Frank' }, { id: 7, name: 'Grace' }]; array.push(...objectsToAdd); // Frank and Grace join the bash - double trouble!

Dynamic guest list

For quick invite decisions, automate the process with a function:

function addGuest(guestList, guest) { guestList.push(guest); return guestList; } let newComer = { id: 8, name: 'Hank' }; addGuest(guests, newComer); // Hank breezes in. Where's the barbecue?

Keeping the guest list intact

In shared houses, avoid mutually exclusive guest lists. Use Object.freeze() to prevent unwanted changes:

Object.freeze(array); // Party crashers are turned away at the door.

Notice, this does not deep freeze the objects inside the array.

Merging fellow invitees

Connect two guest lists without influencing the original ones with concat():

let additionalGuests = [{ id: 9, name: 'Ivy' }]; let biggerParty = guests.concat(additionalGuests); // Ivy brings the party van.

Behold, this approach won't mess your original guest list—it creates a new one!