How to Replace an Object in an Array with Another Object Based on Property ?
Last Updated :
02 Feb, 2024
In JavaScript, replacing an object in an array with another object based on a specific property involves identifying and updating elements within the array. This task is essential when modifications to individual objects are required, such as updating values or swapping objects based on a particular property criteria.
Using map()
This method used the map function to create a new array by iterating over the original array. It checks a specific property to identify the target object for replacement. If the condition is met, a new object with updated values is returned; otherwise, the original object is retained.
Example: Demonstrate the creation of a new array by applying a function to each element in the existing array using a map().
JavaScript
const books = [
{ title: "Book1", isbn: "12345", edition: 1 },
{ title: "Book2", isbn: "67890", edition: 2 },
{ title: "Book3", isbn: "54321", edition: 1 },
];
const updatedBooksMap = books.map((book) => {
if (book.isbn === "67890") {
return { ...book, edition: 3 }; // Replace edition with a new value
}
return book;
});
console.log(updatedBooksMap);
Output[
{ title: 'Book1', isbn: '12345', edition: 1 },
{ title: 'Book2', isbn: '67890', edition: 3 },
{ title: 'Book3', isbn: '54321', edition: 1 }
]
Using findIndex() and splice()
The findIndex method is used to locate the index of the object in the array based on a specific property. If the index is found, the splice function is used to replace the existing object with a new one. This approach directly modifies the original array.
Example: Demonstration to find the index of the element based on the property using findIndex and then replace concatenate using splice.
JavaScript
const books = [
{ title: "Book1", isbn: "12345", edition: 1 },
{ title: "Book2", isbn: "67890", edition: 2 },
{ title: "Book3", isbn: "54321", edition: 1 },
];
const indexToReplace =
books.findIndex((book) => book.isbn === "67890");
if (indexToReplace !== -1) {
const updatedBooksSplice = [...books];
updatedBooksSplice.splice(indexToReplace, 1, {
...books[indexToReplace],
edition: 3,
});
console.log(updatedBooksSplice);
}
Output[
{ title: 'Book1', isbn: '12345', edition: 1 },
{ title: 'Book2', isbn: '67890', edition: 3 },
{ title: 'Book3', isbn: '54321', edition: 1 }
]
Using filter() and concat()
The filter method is applied to exclude the object to be replaced, and the concat function is used to append a new object with updated values. This method creates a new array without modifying the original one, making it suitable for scenarios where immutability is desired. It offers a clean and declarative way to achieve the replacement.
Example: In this, filter out the object to be replaced using the filter function and then concatenate the new object using the concat.
JavaScript
const books = [
{ title: "Book1", isbn: "12345", edition: 1 },
{ title: "Book2", isbn: "67890", edition: 2 },
{ title: "Book3", isbn: "54321", edition: 1 },
];
const updatedBooksFilterConcat = books
.filter((book) => book.isbn !== "67890")
.concat({ title: "Book2", isbn: "67890", edition: 3 });
console.log(updatedBooksFilterConcat);
Output[
{ title: 'Book1', isbn: '12345', edition: 1 },
{ title: 'Book3', isbn: '54321', edition: 1 },
{ title: 'Book2', isbn: '67890', edition: 3 }
]
Similar Reads
How to Update an Array of Objects with Another Array of Objects using Lodash? Updating an array of objects with another array of objects involves merging or updating objects in the first array with corresponding objects from the second array. Below are the approaches to updating an array of objects with another array of objects in the Lodash library:Table of ContentUsing loda
4 min read
Updating a Property of an Object in an Array within a MongoDB Document In MongoDB, it's common to store complex data structures within documents, including arrays of objects. Updating the property of an object within such an array can be a frequent requirement in many applications. This article will explore various methods to achieve this task, covering concepts like a
3 min read
How to Remove a Property from All Objects in an Array in JavaScript? To remove a property from all objects in an array in JavaScript, you can use the forEach() method to iterate over each object in the array and use the delete operator to remove the specified property.Example:JavaScriptconst arrayOfObjects = [ { name: "Alice", age: 25, city: "New York" }, { name: "Bo
2 min read
How to Check Presence of a Specific Object Property in an Array ? Checking for the presence of a specific object property in an array involves determining whether any object within the array possesses the specified property. This task is commonly encountered when working with arrays of objects and needing to verify if a particular property exists across any of the
3 min read
How to modify an object's property in an array of objects in JavaScript ? Modifying an object's property in an array of objects in JavaScript involves accessing the specific object within the array and updating its property.Using the Array.map() methodUsing the map() method to create a new array by transforming each element of the original array based on a specified funct
5 min read
How to copy properties from one object to another in ES6 ? The properties of one object can be copied into another object through different methods. Here are some of those methods. Object.assign(): By using the Object.assign() method, all enumerable properties of one or more source objects are copied to the target object. This method returns the modified ta
3 min read
How to Add Duplicate Object Key with Different Value to Another Object in an Array in JavaScript ? Adding duplicate object keys with different values to another object in an array in JavaScript refers to aggregating values under the same key from multiple objects in an array, creating a new object where each key corresponds to an array of associated values. Table of Content Using for...of LoopUsi
4 min read
Remove Array Element Based on Object Property in JavaScript Here are the several methods that can be used to remove array elements based on object property in JavaScript1. Using the filter() methodThe filter() method is useful if you want to preserve the original array and create a new one without the element(s) you want to remove.JavaScriptlet a = [{ id: 1,
4 min read
How to Filter an Array of Objects Based on Multiple Properties in JavaScript ? Filtering an array of objects based on multiple properties is a common task in JavaScript. It allows us to selectively extract items from an array that satisfy specific conditions. We will explore different approaches to achieve this task.These are the following approaches:Table of ContentUsing the
6 min read
How to Convert an Array of Objects into an Array of Arrays ? An Array of objects is an array that contains multiple objects as its elements which can be converted into an array of arrays i.e. an array that contains multiple arrays as its elements. There are several methods listed below to achieve this task. Table of Content Using Object.keys() and Object.valu
3 min read