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 use array that include and check an object against a property of an object ? Array.includes() Method: In JavaScript, includes() method is used to determine that a particular element is present in an array or not. It returns true if the element is present and false when it is absent. Syntax: array_name.includes(searchElement, ?fromIndex) Parameters: searchElement: The element
3 min read
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 Sort an Array of Objects Based on a Key in JavaScript ? In JavaScript, sorting an array of objects based on the key consists of iterating over the array, applying the sort() method or other approaches, and arranging the array in the desired sorting order. Table of Content Using sort() methodUsing Custom Sorting FunctionUsing Lodash _.orderBy() MethodUsin
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
How to get the Index of an Array based on a Property Value in TypeScript ? Getting the index of an array based on a property value involves finding the position of an object within the array where a specific property matches a given value. The below approaches can be used to accomplish the task. Table of Content Using Array.findIndex()Using reduce() methodUsing for loopUsi
4 min read