[英]React-Native remove object from Array
我正在嘗試從陣列中刪除 object,盡管我不確定如何獲取 object,這基本上使編寫的代碼不會產生任何作用。
讓我展示現有的數組:
Object {
"created_at": "2020-06-30T11:22:53.000000Z",
"icon": "subjectImgs/509-1080x1080.jpg",
"id": 2,
"name": "Test",
"updated_at": "2020-06-30T11:22:53.000000Z",
"user_id": 1,
},
Object {
"created_at": "2020-06-04T18:32:25.000000Z",
"icon": "subjectImgs/698-1080x1080.jpg",
"id": 1,
"name": "history",
"updated_at": "2020-06-04T18:32:25.000000Z",
"user_id": 1,
},
Object {
"created_at": "2020-07-08T16:32:03.000000Z",
"icon": "subjectImgs/698-1080x1080.jpg",
"id": 21, // Here is the ID
"name": "123",
"updated_at": "2020-07-08T16:32:03.000000Z",
"user_id": 1,
},
}
監聽事件時,我得到剛剛刪除的 object 的數組:
Object {
"socket": null,
"subject": Object {
"created_at": "2020-07-08T16:32:03.000000Z",
"icon": "subjectImgs/698-1080x1080.jpg",
"id": 21, // Here is the ID
"name": "123",
"updated_at": "2020-07-08T16:32:03.000000Z",
"user_id": 1,
},
}
現在,我嘗試刪除它的方式如下:
.listen('SubjectRemoved', ev => {
var array = this.state.subjects
this.setState({ subjects: array.filter((id) => id != ev.subject.id) })
});
但顯然,這是行不通的。 我假設因為使用id
真的一無所獲。
我認為問題出在過濾方法中:
array.filter((id) => id != ev.subject.id) // here id is an elemt of the array not the real id
你可以試試
array.filter((subject) => subject.id != ev.subject.id) //if is an array of subjects
或者
array.filter((elem) => elem.subject.id != ev.subject.id) //if is an array of objects like {socket: null, subject: {... with the fields }}
如果您認為ev.subject.id
不起作用,您可以在過濾器語句之前 console.log 它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.