Csati
Csati

Reputation: 1271

OOP/JavaScript - Delete object when deleting reference

teachers = [{name: 'Mary'},{name: 'Karen'}]

students = [{name: 'Joe'},{name: 'Bill'}]

courses = [{
  name: 'math',
  teacher: teachers[0],
  students: [students[0]],
}]

When deleting an item in the teachers array, all items in the courses array with reference to that teacher object should be deleted, too. Is there a way or pattern for doing it without iterating through all items in courses array? (The real world application is much more complicated.)

Upvotes: 1

Views: 66

Answers (2)

Aleksander
Aleksander

Reputation: 36

If you can save courses in new WeakMap() it will solve your issue.

const coursesWeekMap = new WeakMap();
coursesWeekMap.set(teachers[0], {
  name: 'math',
  teacher: teachers[0],
  students: [students[0]],
});

Upvotes: 2

daveyfaherty
daveyfaherty

Reputation: 4613

Is there a way or pattern for doing it without iterating through all items in courses array?

Not really, but a filter is an easy way to do this, you should do it before deletion, for the sake of neatness.

const deletedTeacher = {name: 'Mary'};
const changedCourses = courses.filter(c => c.teacher.name !== deletedTeacher.name);

// delete teacher from array whatever way you like, confirm that it has happened

courses = changedCourses

Upvotes: 0

Related Questions