“Find and Replace Object in Array JavaScript” refers to a JavaScript process that allows you to locate an object within an array and replace it with another object.
You can also replace an object with a different type of object in an array. In this article, we are going to discuss every aspect of finding and replacing objects in an array in JavaScript.
The two basic use cases for finding and replacing objects within an array are as follows: One is to search through an array for a single item, then change a few of its properties. One more is to update every object in an array that meets a particular set of search parameters.
Keep in mind that if you need to find and replace only a single object within an array, then it’s best to use the Array.findIndex() method. But if you would like to find and replace multiple objects instead of a single one, then use the Array.filter() method.
There are some more tricks that you need to meet your requirements perfectly. We will cover those in our following code examples. So bear with us till the end.
Table of Contents
Find and Replace Object in an Array JavaScript with the Same Object Structure
Example of Single Object Find and Replace in an Array
Assume a common scenario where we have an array of order objects and we need to update or replace a specific order object or its property within the array. To do that, we have to first find the order object by using the Array.findIndex() method, and then replace its property with another object using the simple JS assignment operator.
<script>
const ordersArray = [
{id: 1, item: "JavaScript Course", bProcessed: true },
{id: 2, item: "CSS Course", bProcessed: true },
{id: 3, item: "HTML Course", bProcessed: false },
{id: 4, item: "Tailwind Course", bProcessed: true },
{id: 5, item: "Angular Course", bProcessed: false },
{id: 6, item: "Advance Course", bProcessed: true },
];
// order object updated. Need to adjustment the array
const updatedOrder = {id: 3, item: "HTML Course", bProcessed: true };
// Find object in an array
const getIndex = ordersArray.findIndex(obj => obj.id === updatedOrder.id);
// How to update an object in an array in JavaScript?
// find and replace object in array javascript
ordersArray[getIndex] = updatedOrder;
console.log(ordersArray);
</script>
Output: Find and Replace Object in Array JavaScript Example
Code Explanation
In the above code, we use the Array.prototype.findIndex() method to get a specific order based on the order ID. Since the order ID (here 3) that we need to update matches the 3rd object of the ordersArray, we will get index number 2 as a return value. Now, just replace the third object with the updated order object. Just take a look at the output image mentioned above to see the effect.
If you are uncomfortable with JS arrow function you can use general function as findIndex() method callback function. Look at the following code:
function getUnprocessedOrders(element) {
return element.bProcessed===false;
}
// order object updated. Need to adjustment the array
const updatedOrder = {id: 3, item: "HTML Course", bProcessed: true };
// Find object in an array
const getIndex = ordersArray.findIndex(getUnprocessedOrders);
If you look at the output, what did you find? The findIndex() method returns only one object but does not return the object with id=5, though this order is an unprocessed order. This is because the findIndex() method returns the index of the first matched element in an array that satisfies the provided condition.
And finally print the array into the browser console to check object properties.
Example of Multiple Object Find and Replace in an Array
In this example, we are following the same array of objects, ordersArray. Where two orders are in an unprocessed state. And we are going to find those unprocessed orders and update the processed property of the object from false to true.
To get multiple objects, we cannot use the findIndex() method as it returns only the matched first object of an array. To solve this issue, we have to use the Array.filter() method in the following way:
<script>
const ordersArray = [
{id: 1, item: "JavaScript Course", bProcessed: true },
{id: 2, item: "CSS Course", bProcessed: true },
{id: 3, item: "HTML Course", bProcessed: false },
{id: 4, item: "Tailwind Course", bProcessed: true },
{id: 5, item: "Angular Course", bProcessed: false },
{id: 6, item: "Advance Course", bProcessed: true },
];
function getUnprocessedOrders(element) {
return element.bProcessed===false;
}
var unprocessedOrdersArray=ordersArray.filter(getUnprocessedOrders);
// you can also use JS arrow function
// var unprocessedOrdersArray=ordersArray.filter((obj)=> obj.bProcessed==false);
// find and replace object in array javascript
// update multiple objects at a time
unprocessedOrdersArray.forEach((obj) => obj.bProcessed=true);
console.log(ordersArray);
</script>
Output: JS Find and Replace Objects within an Array
3 important points of the Array.filter() method:
- Creates a new array that satisfies the provided test expression (arrow function or custom callback function).
- Does not execute the callback function for empty elements of the specified array.
- Does not change the original array, which means ordersArray in our case.
Find and Replace Object in an Array JavaScript with the Different Object Structure
Single Object Find and Update Object in array JavaScript Example
We follow the same array of objects ordersArray here in the following example to demonstrate how we can find and replace an object within an array with another different type of object.
<script>
const ordersArray = [
{id: 1, item: "JavaScript Course", bProcessed: true },
{id: 2, item: "CSS Course", bProcessed: true },
{id: 3, item: "HTML Course", bProcessed: false },
{id: 4, item: "Tailwind Course", bProcessed: true },
{id: 5, item: "Angular Course", bProcessed: false },
{id: 6, item: "Advance Course", bProcessed: true },
];
// The data structure is different comparing orderArray objects
// How to replace an object in an array in JavaScript?
const updatedOrder = {id: 3, item: "HTML Course", bProcessed: true, bDelivered: true };
// Find object in an array
const getIndex = ordersArray.findIndex(obj => obj.id === updatedOrder.id);
// find and replace object in array javascript
ordersArray[getIndex] = updatedOrder;
// if you want to keep same structure
// The additional object property bDelivered not updated
//ordersArray[getIndex].bProcessed = updatedOrder.bProcessed;
console.log(ordersArray);
</script>
Output is the is the same as in the in the earlier single object modification example.
If you want to use a custom function instead of an arrow function, you can do that as well. Just follow our above examples. In case of issues, just leave a comment. We will update the article accordingly. We are just skipping this part to keep the article simple and easy to read.
Multiple Object Find and Update Object in array JavaScript Example
Like earlier, use the Array.filter() method instead of the findIndex method to get all unprocessed orders at a time. You can find and replace objects in an array in JavaScript if the structures of the objects are different.
<script>
const ordersArray = [
{id: 1, item: "JavaScript Course", bProcessed: true },
{id: 2, item: "CSS Course", bProcessed: true },
{id: 3, item: "HTML Course", bProcessed: false },
{id: 4, item: "Tailwind Course", bProcessed: true },
{id: 5, item: "Angular Course", bProcessed: false },
{id: 6, item: "Advance Course", bProcessed: true },
];
// The data structure is different from orderArray
const updatedOrder = {id: 3, item: "HTML Course", bProcessed: true, bDelivered: true };
// Find objects from an array
// javascript find in array of objects
const unprocessedOrdersArray = ordersArray.filter(obj => obj.bProcessed==false);
// find and replace object in array javascript
unprocessedOrdersArray.forEach((obj) => obj.bProcessed=updatedOrder.bProcessed);
console.log(ordersArray);
</script>
Output is the is the same as in the in the earlier multiple object modification example.
Conclusion
To achieve “find and replace object in array javascript”, We have discussed almost every scenarions from single object find and replacement to multiple object find and replacement in an array. We also covered the use cases for differently structured objects also.
Use findIndex() method if you need to find and replace only one object within an array irrespective to object structure.
Use filter() method if you need to find and replace multiple objects within an array irrespective to object structure.
Happy Coding!!
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply