How to change value of object which is inside an array using JavaScript or jQuery?
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:
Modifying without mutating
JavaScript's badass map
is on rescue when changing the original array is a crime scene:
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:
Be swift with ternaries
Do a swift conditional update within map
using ternary operators. Like a caffeinated writer at a typewriter:
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:
Want to update a passenger (object's value) in the second carriage?
Checking existence before updating
Before proceeding to update, ensure the object does exist in the array. This prevents you from updating some ghost object:
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.
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
Was this article helpful?