In JavaScript, it is often required to update the values of objects stored in arrays. This allows modifying properties of existing objects dynamically instead of creating new objects whenever a change is needed.
There are several useful methods in JavaScript to update objects in arrays, such as:
findIndex()
forEach()
map()
- Using index positions
- Using traditional loops like
for
andwhile
In this comprehensive guide, we will explore these approaches with code examples to update object values in JavaScript arrays.
Introduction to Updating Objects in JavaScript Arrays
Unlike primitive data types like strings, numbers etc., objects and arrays are reference data types in JavaScript. This means variables don’t actually store the object, rather they store a reference to the location in memory where the object is stored.
For example:
let person = {
name: "John",
age: 30
};
let updatedPerson = person; //updatedPerson stores reference to person object
Here updatedPerson
points to the same person object. So if we do:
updatedPerson.name = "Harry"; //update property
console.log(person.name); // "Harry"
console.log(updatedPerson.name); // "Harry"
Both prints show the update because updatedPerson and person point to the same object.
This reference behavior allows modifying objects by simply updating properties instead of recreating updated objects from scratch.
Now let‘s see how to apply this to update objects stored in arrays.
1. Using findIndex() Method
The findIndex()
method returns the index of the first element in an array that satisfies a test condition. We can use this to get the index of the object to update.
For example:
const users = [
{ id: 1, name: "John"},
{ id: 2, name: "Peter"}
];
const findIndex = users.findIndex(user => user.id === 1); //get index of id:1
users[findIndex].name = "Harry"; //update name property
console.log(users[findIndex]); // {id: 1, name: "Harry"}
Here:
findIndex()
returns index0
for object withid
of 1.- We use this index to update
name
property of that object - The log shows updated name
The key thing is using the index from findIndex()
to access and update the object stored in the array.
Let‘s see another example with more details:
const users = [
{ id: 1, name: "John", age: 25},
{ id: 2, name: "Mary", age: 23},
{ id: 3, name: "Steve", age: 28}
];
console.log("Users before update: ", users);
const user = users.findIndex(u => u.id === 2);
users[user].name = "Cindy";
users[user].age = 21;
console.log("Users after update: ", users);
Output:
Users before update:
[
{ id: 1, name: ‘John‘, age: 25 },
{ id: 2, name: ‘Mary‘, age: 23 },
{ id: 3, name: ‘Steve‘, age: 28 }
]
Users after update:
[
{ id: 1, name: ‘John‘, age: 25 },
{ id: 2, name: ‘Cindy‘, age: 21 },
{ id: 3, name: ‘Steve‘, age: 28 }
]
Here we retrieved the index of the user object with id
of 2, then directly updated the name
and age
properties of that object in the array.
Some key pointers about using findIndex()
:
- It searches array based on condition, so useful for targeting update if you know any unique property like id
- Access the object to update using returned index
- Can update single or multiple properties
With this approach you don‘t need to loop through the array yourself to find and update objects. findIndex()
handles that internally.
Next let‘s see how we can use forEach
method to achieve the same objective.
2. Using forEach Method
The forEach()
method provides a simple way to iterate over all elements in an array. We can use it update objects like this:
const users = [
{ id: 1, name: "John", age: 25},
{ id: 2, name: "Peter", age: 23},
{ id: 3, name: "Harry", age: 28}
];
users.forEach(user => {
if(user.id === 2) {
user.name = "Mary";
user.age = 26;
}
});
console.log(users);
Working:
forEach
iterates over eachuser
object- Inside we check
id
property to target required object - Updates are done directly on the
user
being iterated
Here we don‘t need to get index separately like findIndex()
. Instead we get direct access to each object allowing easy check and update.
However, forEach
can‘t break based on condition (always completes full iteration). So if the target element is found early in the array, it would still loop through remaining elements needlessly.
Let‘s look at one more example with forEach()
:
const products = [
{ id: 1, name: "T-shirt", category: "clothing" },
{ id: 2, name: "Shoes", category: "footwear" },
{ id: 3, name: "Watch", category: "accessories" }
];
products.forEach((product) => {
if(product.category === "clothing") {
product.name = "Jeans";
}
});
console.log(products);
Output:
[
{ id: 1, name: "Jeans", category: "clothing" },
{ id: 2, name: "Shoes", category: "footwear" },
{ id: 3, name: "Watch", category: "accessories" }
]
So in summary, forEach()
allows directly accessing and updating objects but iterates over complete array always.
Up next we have the map()
method to update objects in array.
3. Using map() Method
The map()
method transforms array by applying a function to all elements. It also returns a new array.
We can utilize this to transform objects in array by updating properties:
const users = [
{ id: 1, name: "Amy"},
{ id: 2, name: "Mike"}
];
const updatedUsers = users.map(user => {
if(user.id === 2){
return {...user, name:"John"};
}
return user;
});
console.log(updatedUsers);
Working:
map()
executes callback for eachuser
- If id matches, return new object with updated name property using object spread
...user
syntax - Else return user unchanged
- Finally returns new transformed array
Some key things for map()
:
- Returns new array so need to capture it
- Allows modifying object immutably by returning new one
- Doesn‘t update in-place like forEach
Let‘s see how we can do multiple property updates:
const products = [
{ id: 1, name: "T-shirt", price: 20 },
{ id: 2, name: "Shoes", price: 50}
];
const updated = products.map(item => {
if(item.id === 1) {
return {...item, name:"Shirt", price: 25};
}
return item;
});
console.log(updated);
This is updating both name
and price
properties selectively.
So in summary, map()
returns a new updated array while also giving control over how objects are immutably updated.
Up next we‘ll see how indexing can be used to update objects.
4. Using Index Position
Since arrays are essentially indexed data structures, we can also rely on the index position to update specific objects.
For example:
const tasks = [
{ id:1, title:"Task 1" },
{ id:2, title:"Task 2" }
];
const index = tasks.findIndex(task => task.id === 2);
tasks[index].title = "Updated Task 2 title";
console.log(tasks[index]);
Here:
- Get index of target object using
findIndex()
- Use index position to directly access object and update property
- Log updated object
We can also use a simple loop to generate indexes:
const books = [
{ id: "1", title: "Book 1"},
{ id: "2", title: "Book 2"},
{ id: "3", title: "Book 3"}
];
for(let i = 0; i < books.length; i++){
if(books[i].id === "2"){
books[i].title = "Harry Potter";
}
}
console.log(books);
So index position gives basic access to update objects stored in arrays.
However, manually getting indexes and validating id/other property before updating can be tedious compared to methods like findIndex()
etc.
Nonetheless, it‘s simple and gets the job done!
5. Using for and while Loops
Along with the functional methods, we can also use traditional loops like for
and while
to iterate and update objects in array.
Here is an example with for
loop:
const users = [
{ id: 1, name: "John"},
{ id: 2, name: "Mike"},
{ id: 3, name: "Mary"}
];
for(let i = 0; i < users.length; i++) {
let user = users[i];
if(user.name === "Mike") {
user.name = "Michael";
}
}
console.log(users);
And similar one with while
loop:
const products = [
{ id: "1", name: "T-Shirt"},
{ id: "2", name: "Shoes"}
];
let i = 0;
while(i < products.length) {
if(products[i].id === "2") {
products[i].name = "Sandals";
}
i++;
}
console.log(products);
In both cases:
- Used loop counter to access objects
- Updated object if condition matches
- Loops iterates over full array
So regular loops can also get the job done!
Now that we have covered a variety of approaches, let‘s talk about use cases and recommendations.
Which Method Should Be Used?
All above methods can update objects stored in arrays but which one to use depends on your specific requirements:
findIndex()
– Great when you need to find and update object with specific known property like id. Single method to handle search and update.forEach()
– Provides direct access to array objects. Simple way for iterative updates but can‘t break early.map()
– Useful for immutable update. Returns new updated array. Additional control over update.- Index Position – Basic and direct way but manual search/validation is needed.
- Loops – Same benefits/limitations as
forEach()
. Functional methods usually preferred.
Here is a quick recommendation guide on which one to use:
- When target object has unique ID –
findIndex()
- Need simple iteration with direct access –
forEach
- Require immutable update and new array –
map()
- Just need basic index update – Index Position
- Already using loops in code –
for
/while
This should help decide the right method for your situation.
Conclusion
Updating objects in JavaScript arrays is needed quite often. Whether it is changing some properties or replacing entire object, there are a variety of useful ways to handle it:
findIndex()
easily finds object and updates using returned indexforEach()
directly accesses each object allowing updatesmap()
returns new transformed array with updated objects- Index position provides basic access to array objects
- Traditional loops like
for
andwhile
can also iterate over objects
The right method would depend on the specific requirements like simplicity, immutability, performance etc. But in most cases findIndex()
, forEach()
and map()
should have you covered.
I hope this guide gave you a good overview of how to update objects stored in arrays using modern JavaScript capabilities. Each method was explained with examples to highlight their working and use cases.
Updating objects arrays is needed regularly in JavaScript programming. Feel free to apply these techniques in your own code!