Explain Codes LogoExplain Codes Logo

Add property to an array of objects

javascript
javascript-best-practices
functional-programming
performance-optimization
Anton ShumikhinbyAnton Shumikhin·Jan 28, 2025
TLDR

The key to extending every object in an array is the sweet duet of .map() and the spread operator (...). Let's boil it down:

let expandedArray = [{ id: 1 }, { id: 2 }].map(obj => ({ ...obj, extraProp: 'value' }));

Voila! Now we've got an array with the extraProp:

[ { id: 1, extraProp: 'value' }, { id: 2, extraProp: 'value' } ]

...obj guarantees that all original properties are retained, and offers a seamless merge with the new one.

Deep dive: methods and considerations

To mutate or not to mutate?

You have two choices: tinker with the original array, or spawn a brand new one. .map() births a new array — a good practice to prevent side effects. But if the original array is what you're into, forEach or a for...of loop hits the mark.

Old guard vs. New school

While the spread syntax is flashy, it may not play nice in older environments. Here, Object.assign() is your seasoned ally, offering similar capabilities but with wider acceptance:

array.forEach(obj => Object.assign(obj, { extraProp: 'default' }));

Joke Alert 🚨

/* Whoever said "respect your elders" clearly excluded old JavaScript environments. */

Loop-de-loops and direct hits

Direct assignment within for...of loops is a classic approach, offering the reins to control the loop iteration:

for (let obj of array) { obj.extraProp = 'default'; }

Joke Alert 🚨

/* for...of loops: The Willy Wonka of JavaScript. */

Welcome to the lodash jungle!

Fan of utilities libraries like Lodash? Add properties using _.set():

_.each(array, obj => _.set(obj, 'extraProp', 'default'));

Joke Alert 🚨

/* lodash: The Swiss Army Knife of JavaScript. */

The Fortress of Immutability

Working with React or someone else from the functional programming family? In that case, immutability is the queen. Always return a new array rather than messing with the old one: Preserve the puritanical state.

Test now, not fester later

Adding new properties to an array of objects? Test, test, test!. Be certain all objects get updated accordingly and avoid pesky side effects.

Spotting and fixing common issues

The Dark Side of Mutation

Mutating the original array might lead to unforeseen glitches in certain contexts. Be sure, know whether your operation is creating a new array or meddling with the existing one.

Avoiding Property Landmines

Plan ahead, ensure your new property doesn't overlap with existing keys to avoid overwriting values accidentally.

Getting to the Bottom of Nested Objects

In case your objects come bundled with nested structures, remember that spread syntax and Object.assign() offer only a shallow copy. For deep cloning, you might require utilities like _.cloneDeep() from Lodash.

Overcoming the Wall of Performance

Deep waters run slow. When dealing with sizable datasets, watch for a speed bump. A for loop is typically quicker than .map() or .forEach(), although differences might not surface until the array balloons quite a bit.