Replace an object in an array with another object in JavaScript

In this tutorial, I will show how you can replace an object in an array with another object in JavaScript.

Here are some methods below to replace an object in an array with another object.

Using splice() method

The splice() method modifies an array of elements by deleting or swapping out existing ones or inserting new ones in their place. The method accepts three arguments:

  • The index at which to begin modifying the array.
  • The number of array elements to delete (if any).
  • The new array element(s) to be added (if any).

JavaScript program to replace an object in an array with another object.

const myArray = [
  {name: 'Sam', age: 24}, 
  {name: 'Rayan', age: 26}
];
//Defining the object by which we want to replace
const myObject = {name: 'David', age: 28};

//To find the index of the object that we want to replace
const index = myArray.findIndex(item => item.name === 'Rayan');

//To replace the object with the new object 
myArray.splice(index, 1, myObject);

console.log(myArray);

In the above program, the findIndex method searches through myArray and returns the index of the first element that satisfies the provided testing function, in this case item => item.name === 'Rayan'.

Once the index of the object to replace is found (1 in this case), the splice method is used to remove one element at that index and replace it with myObject. The resulting modified array is logged to the console using console.log(myArray)method.

Output:

[ { name: 'Sam', age: 24 }, { name: 'David', age: 28 } ]

Using map() method

With the map() method, we can replace an object in an array with another object. This function allows us to loop around an array. Conditional statements will also be used to determine when to replace the object.

JavaScript program to replace an object in an array with another object using map() method and conditional statement.

const myArray = [
  {name: 'Sam', age: 24}, 
  {name: 'Rayan', age: 26}
];

//Defining the object by which we want to replace
const myObject = {name: 'David', age: 28};

const updatedArray = myArray.map(obj => {
  // Check if the name property of the current object is 'Rayan'
  if (obj.name === 'Rayan') {
    // If it is, return a new object with the updated name and age properties
    return  myObject;
  }
  // Otherwise, return the original object
  return obj;
});

console.log(updatedArray);

Output:

[ { name: 'Sam', age: 24 }, { name: 'David', age: 28 } ]

Leave a Reply

Your email address will not be published. Required fields are marked *