0

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.

1

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks DeborahK. However I'm confused on how that replaces the course in my array with myCourse?
I did a stackblitz. See revised answer.
0

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;
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.