[英]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.删除teachers
数组中的项目时, courses
数组中与该teacher
object 相关的所有项目也应删除。 Is there a way or pattern for doing it without iterating through all items in courses
array?有没有一种方法或模式可以在不遍历courses
数组中的所有项目的情况下做到这一点? (The real world application is much more complicated.) (现实世界的应用程序要复杂得多。)
If you can save courses
in new WeakMap()
it will solve your issue.如果您可以将courses
保存在new WeakMap()
中,它将解决您的问题。
const coursesWeekMap = new WeakMap();
coursesWeekMap.set(teachers[0], {
name: 'math',
teacher: teachers[0],
students: [students[0]],
});
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.