简体   繁体   中英

How to remove an element in an object array by the content of a field? (map returning undefined)

I'm trying to implement a todo list in React. I have a state that stores id and content of each task:

this.state = {tasks: [{id: 123, content: 'Walk with dog'}, {id: 2, content: 'Do groceries'}]} 

I managed to add elements by using

this.setState([...this.state.tasks, newTask])

However, I'm struggling to remove elements. I thought about using a map:

this.state.tasks.map((task)=>{
   if(task.id != 123){return task}
})

However, it's appending undifened elements when the id is found, instead of nothing.

地图返回未定义

What should I do?

You can use the filter method to filter items in your array:

 let filtered = tasks.filter(task => task.id != 123)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM