简体   繁体   中英

How to remove item from array knockout

I am using knockout.js library. I am trying to using knockout arrayRemoveItem utility function but it seems that its not working. Here is my code :

JS

function VM()
{
  this.Items = [{id:'1', name:'A'}, 
                {id:'2', name:'B'}, 
                {id:'3', name:'C'}, 
                {id:'4', name:'D'}
               ];

  this.Delete = function(){
    console.log(this.Items);          //before removing

    ko.utils.arrayRemoveItem(this.Items, function(item){
      return item.id == '3';
    });

    console.log(this.Items);          //after removing
  };
}

Fiddle

If you check the console after pressing delete button, item 3 is not removing from array. What i am missing here?

The arrayRemoveItem takes the items to be removed as the second argument like ko.utils.arrayRemoveItem(array, itemToRemove) , so you need to first find the object and pass it to arrayRemoveItem .

Try

function VM()
{
  this.Items = [{id:'1', name:'A'}, 
                {id:'2', name:'B'}, 
                {id:'3', name:'C'}, 
                {id:'4', name:'D'}
               ];

  this.Delete = function(){

    var item;
    ko.utils.arrayForEach(this.Items, function(v) {
      if(v.id == '3'){
        item = v;
      }
    });

    console.log(this.Items);
    ko.utils.arrayRemoveItem(this.Items, item);
    console.log(this.Items);
  };
}

ko.applyBindings(new VM());

Demo: Fiddle

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