Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - Knockout : Remove array element by specific field value

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...