简体   繁体   中英

Delete particular objects from array in javascript

I have a object of array stored in local-storage as shown below

  var todos = [
    {"id":0,"text":"Make lunch","completed":true},
    {"id":1,"text":"Do laundry","completed":false},
    {"id":2,"text":"Complete Project","completed":true}
  ]

How can i delete all objects that are completed? Please tell me how to delete it with splice method as i cant replace array i want to just remove it from array!(as my project requirements) Thanks for any help

您可以尝试使用javascript array.filter

todos=todos.filter(todo=>!todo.completed);

这样的事情会做的

var filteredAry = todos.filter(function(e) { return e.competed !== 'true' })

You can filter uncompleted todos like:

const unCompletedTodos = todos.filter(todo => !todo.completed);

Also you don't have to use const you can use var but I recommend you to use const or let instead of var

var todos = [
{"id":0,"text":"Make lunch","completed":true},
{"id":1,"text":"Do laundry","completed":false},
{"id":2,"text":"Complete Project","completed":true} ];

var inCompletes = todos.filter(item => !item.completed );

inCompletes will return an array of objects with completed is false.

Output

inCompletes = [{"id":1,"text":"Do laundry","completed":false}];

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