How to use map() In Javascript
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); |
[ { title: 'Book1', isbn: '12345', edition: 1 }, { title: 'Book2', isbn: '67890', edition: 3 }, { title: 'Book3', isbn: '54321', edition: 1 } ]
How to Replace an Object in an Array with Another Object Based on Property ?
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()
- Using findIndex() and splice()
- Using filter() and concat()