![]() |
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. Table of Content 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
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
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
Output
[ { title: 'Book1', isbn: '12345', edition: 1 }, { title: 'Book3', isbn: '54321', edition: 1 }, { title: 'Book2', isbn: '67890', edition: 3 } ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |