Explain Codes LogoExplain Codes Logo

How to change value of object which is inside an array using JavaScript or jQuery?

javascript
map
functions
best-practices
Anton ShumikhinbyAnton Shumikhin·Nov 24, 2024
TLDR

For a fast manipulation of your object within an array, use the findIndex method to quickly locate the object. Then modify its property value like this:

let myArray = [{ id: 1, value: 'a' }, { id: 2, value: 'b' }]; // applying James Bond's strategy - "License to Update" myArray[myArray.findIndex(obj => obj.id == 2)].value = 'updated'; console.log(myArray); // Don't be surprised, the value got updated!

Modifying without mutating

JavaScript's badass map is on rescue when changing the original array is a crime scene:

// Cloning - the no-mutation way using spread operator and map const updatedArray = myArray.map(obj => obj.id === 2 ? { ...obj, value: 'updated' } : obj ); console.log(updatedArray); // Surprise! Original array is untouched.

Break early, not late

Working with large arrays? Use a for loop and break right after the object is found and updated. Like a train stopping at your station:

let index; for (let i = 0; i < myArray.length; i++) { if (myArray[i].id === 2) { index = i; break; // "No more loops, thank you!" } } if (index !== undefined) myArray[index].value = 'updated'; // Object found, mission completed.

Be swift with ternaries

Do a swift conditional update within map using ternary operators. Like a caffeinated writer at a typewriter:

const updatedArray = myArray.map(obj => obj.id === 2 ? {...obj, value: 'updated'} : obj );

Visualizing it

Let's visualize the process of tweaking an array:

Visualize an array as a train (🚂), and each carriage is an object in that array:

Array Train: [🚃(Object 1), 🚃(Object 2), 🚃(Object 3)]

Want to update a passenger (object's value) in the second carriage?

Before: [🚃(👩‍💼), 🚃(👨‍🔧), 🚃(👩‍🚀)] After: [🚃(👩‍💼), 🚃(👨‍🍳), 🚃(👩‍🚀)] // 👨‍🔧 just became 👨‍🍳!

Checking existence before updating

Before proceeding to update, ensure the object does exist in the array. This prevents you from updating some ghost object:

let index = myArray.findIndex(obj => obj.id === 2); if (index !== -1) { myArray[index].value = 'updated'; } else { console.log('Ghost object! Object not found.'); // Data integrity saved. }

Readability or performance - Your call

map promises readability, while for loop leans towards performance. Choose your weapon based on your app's needs.

ES6 for concise codes

Embrace ES6 arrow functions to make your coffee taste better with lesser code.

// Arrow Function - A Saviour of Vertically Challenged Folks (less lines) myArray = myArray.map(obj => obj.id === 2 ? {...obj, value: 'updated'} : obj);

Keep original data intact

However tempting it may be to modify the original data, resist the temptation. This not only helps preserve the initial data but also lessens the oddity for any future bugs