M Jenkins
M Jenkins

Reputation: 53

Replace one element in an Array of Angular model objects with another object using Angular2

I have an array of angular objects. I want to replace an entire element in the array with another element.

    export interface modelCourse{
         var1: number;
         var2: number;
     }

I want to do something like this:

    updateResults(myCourse: modelCourse) {
        this.allCourses.forEach(element => {
            if (myCourse.Id=== element.Id) {
                element = myCourse;  // this part doesn't work as expected
            }
        });
    }

Where

    allCourses: modelCourse[] = [];

And allCourses holds all my courses.

Upvotes: 0

Views: 746

Answers (2)

DeborahK
DeborahK

Reputation: 60548

If you only need to find the one matching element, you don't need to loop through all of the elements, just use the findIndex method. This finds the index of the one element you need without looping through all of them.

You can then use that index to update the original array.

updateResults(myCourse: modelCourse) {
    const foundElementIndex = this.allCourses.findIndex(element => myCourse.id === element.id);
    this.allCourses[foundElementIndex] = myCourse;
}

I did a stackblitz here: https://stackblitz.com/edit/angular-hxxddn

Upvotes: 3

RANJIT PATRA
RANJIT PATRA

Reputation: 864

Please use Array.map to update this.allCourses.

updateResults(myCourse: modelCourse) {
  this.allCourses = this.allCourses.map(element => {
      if (myCourse.Id === element.Id) {
          return myCourse;
      }
      return element;
  });
}

Upvotes: 0

Related Questions