How to use the map method In Javascript
The map() method creates a new array with the results of calling a provided function on every element in the array. In this case, you can check for the property in the current element, and if it matches the desired value, replace it with the new object.
Example: The below example demonstrates the use of map() method to replace an object in an array with another object based on property in JavaScript.
Javascript
const array = [ { id: 1, name: "Java" , fees: "30000" }, { id: 2, name: "Javascript" , fees: "45000" }, { id: 3, name: "Python" , fees: "30000" }, ]; const replaceObj = { id: 2, name: "Web Development" , fees: "35000" }; const newArray = array.map((obj) => obj.id === replaceObj.id ? replaceObj : obj ); console.log(newArray); |
[ { id: 1, name: 'Java', fees: '30000' }, { id: 2, name: 'Web Development', fees: '35000' }, { id: 3, name: 'Python', fees: '30000' } ]
How to Replace an Object in an Array with Another Object Based on Property ?
In JavaScript, an array is a data structure that can hold a collection of values, which can be of any data type, including numbers, strings, and objects. When an array contains objects, it is called an array of objects.
Table of Content
- Using findIndex and splice methods
- Using filter and concat methods
- Using the map method