我有一个像这样的数组......
const students = [
{id:1, name:'ben james', major: 'BIO'},
{id:2, name:'natasha sampson', major: 'ZOO'},
{id:3, name:'keith franklyn', major: 'CHM'},
...
]
我有我的removeStudents()按钮onClick函数,它将获取学生ID并将其从学生阵列中删除:
const id = event.target.id;
const students = this.state.students;
const newArr = students.filter(student => {
student.id != event.target.id;
});
console.log(newArr); // will return []
不幸的是,这不起作用。它擦拭整个阵列清洁。如何根据它的id删除数组中的学生对象?
答案 0 :(得分:2)
传递给filter()
方法的箭头函数不会返回任何内容。添加return
关键字:
const newArr = students.filter(student => {
return student.id != event.target.id;
});
或摆脱花括号:
const newArr = students.filter(student => student.id != event.target.id);