2016-08-20 128 views
0

我有一個這樣的數組...帶過濾器陣列中刪除對象將刪除整個陣列

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的數組中的學生對象?

回答

2

傳遞給filter()方法的箭頭函數不返回任何內容。無論是添加return關鍵字:

const newArr = students.filter(student => { 
    return student.id != event.target.id; 
}); 

或擺脫大括號:

const newArr = students.filter(student => student.id != event.target.id);