How to update array of object from another object array?

How to update array of object from another object array?

Problem Description:

I have two object arrays. One is main array and another one is temp array. I need to compare main array with temp array and based on matching id, I have update the value in the main array from temp array.

For example, id 2 & 3 is matching in both the arrays. So I need to update value in the main array from temp array.

// Main array
this.MyArray = [
    { id: "0", value: "Car" },
    { id: "1", value: "Bike" },
    { id: "2", value: "Train" },
    { id: "3", value: "Bus" },
    { id: "4", value: "Van" }
]

// temp array
this.tempArray =[
    { id: "2", value: "Car" },
    { id: "3", value: "Jet" },
]

//Expected Output in the Main array:
this.MyArray = [
    { id: "0", value: "Car" },
    { id: "1", value: "Bike" },
    { id: "2", value: "Car" },
    { id: "3", value: "Jet" },
    { id: "4", value: "Van" }
]

Solution – 1

  1. Immutable option. Creating a new array based on the "myArray" with updates from the "tempArray":
this.myArray = this.myArray.map((mainObject) => {
  const tempObject = this.tempArray.find((tempObject) => tempObject.id === mainObject.id);

  if (typeof tempObject !== "undefined") {
    return {
       ...mainObject,
       value: tempObject.value,
    };
  }

  return mainObject;
});
  1. Mutable option. Looping over the "tempArray" and replacing the objects in the "myArray" with the relevant object from the "tempArray":
this.tempArray.forEach((tempObject) => {
  const mainObjectIndex = this.myArray.findIndex((mainObject) => mainObject.id === tempObject.id);

  if (mainObjectIndex !== -1) {
    this.myArray[mainObjectIndex] = tempObject;
  }
});

Solution – 2

To update myArray with values of tempArray, you can use the reduce operator, in order to do it in an immutable way :

tempArray.reduce((existingEntries, tempEntry) => {
      const duplicateEntry = existingEntries.find((entry) => entry.id === tempEntry.id)
      if (duplicateEntry && duplicateEntry.value !== tempEntry.value) {
        const duplicateIndex = existingEntries.indexOf(duplicateEntry)
        return [...existingEntries.slice(0, duplicateIndex), tempEntry, ...existingEntries.slice(duplicateIndex + 1)]
      } else {
        return existingEntries
      }
    },
    myArray
  )

Use myArray as the initial value of your new array, and compare the entries contained in your tempArray to check if you should add them or not.

Focus on immutability is a good practice and brings a lot of advantages. This post is explaining properly why you should focus on immutability : What is immutability and why should I worry about it?

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject