Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Javascript – find and replace an object in array

There are 2 cases for searching and replacing an object in a Javascript array:

  • when all the objects in the array share the same structure
  • when the objects in the array have different structures

For both of these cases, we will use the findIndex() method.

Find and replace an object in an array with the same structure

If we have a homogeneous object structure of the array we can just compare the elements in the array based on a specific field:

const myArray = [
  {id: 100, name: "Dan"},
  {id: 101, name: "Bob"},
  {id: 102, name: "Joe"},
]

const searchedObj = {id: 101, name: "Bob"}
const replacingObj = {id: 105, name: "Todd"}

const i = myArray.findIndex(x => x.id === searchedObj.id)
myArray[i] = replacingObj
console.log(myArray)

See the full working codepen here.

Note that we can replace the id property with any other property we want to use as the criteria of object equality. For example:

const i = myArray.findIndex(x => x.name === searchedObj.name)

Find and replace an object in an array with a different structure

In the case of heterogeneous object structure for myArray we cannot rely upon a specific field to test the object equality.

Therefore we will need to write a custom function that it will test if two objects are equal:

const deepEqual = (x, y)=> {
  const ok = Object.keys, tx = typeof x, ty = typeof y;
  return x && y && tx === 'object' && tx === ty ? (
    ok(x).length === ok(y).length &&
      ok(x).every(key => deepEqual(x[key], y[key]))
  ) : (x === y);
}

const myArray = [
   "value 1", 
   {age: 2}, 
   {name: "The dog", age: 2}
]

const searchedObj = {name: "The dog", age: 2}
const replacingObj = {name: "The cat", age: 3}

const i = myArray.findIndex(x => deepEqual(x, searchedObj))
myArray[i] = replacingObj
console.log(myArray)

See the codepen for this example here.

Find and replace multiple occurrences of the same object in an array

Please note that both of the above examples assume that you have only one instance of the searchedObj in myArray.

In case you want to replace multiple occurrences of the searchedObj you can use a classic for loop:

for(let i = 0; i < myArray.length; i++) {
  if(deepEqual(myArray[i], searchedObj.id)) {
    myArray[i] = replacingObj
  }
}

And this concludes our example. If you are interested be sure to check also how the array reduce() function works in Javascript.

Home Screencasts Best of Newsletter Search X