Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to remove ko observable array element by specific field value. I tried one solution. But, there are something missing. It's not working.

customOptionVal : ko.observableArray([])

customOptionVal is ko observableArray and output of that is :

Color: [0: {sub_color: "Red", sub_id: "options_3_2", is_checked: true}
1: {sub_color: "Green + $250.00", sub_id: "options_3_3", is_checked: true}]
Size: {sub_size: "L", sub_id: "options_2_2", is_checked: true}

Now, I want like that if sub_id = options_3_2 then, it will remove from Color element on the base of sub_id.

I tried this below solution. But, it's not working :

$.each(self.customOptionVal()['Color'], function( key, val ) {
                    if(self.customOptionVal()['Color'][key].sub_id == 'options_3_2') {
                        self.customOptionVal.remove(self.customOptionVal()['Color'][key]);
                    }
                });

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
244 views
Welcome To Ask or Share your Answers For Others

1 Answer

The following snippet removes from the customOptionVal observableArray itself -

self.customOptionVal.remove(function(option) {
  return ko.utils.arrayFilter(option.Color, function(color) {
    return color.sub_id === subId;
  });
});

However, if you only want to remove from the Color array (which is not an observableArray), use the following snippet -

self.customOptionVal().forEach(function(option) {
  var index = option["Color"].findIndex(function(y) {
    return y.sub_id === subId;
  });

  if (index > -1) {
    option["Color"].splice(index, 1);
  }

});

Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...