Knockout:按特定字段值删除数组元素

问题描述 投票:0回答:2

我想通过特定的字段值删除ko observable数组元素。我试过一个解决方案。但是,有些东西缺失了。它不起作用。

customOptionVal : ko.observableArray([])

customOptionVal是ko observableArray,输出是:

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}

现在,我希望如果sub_id = options_3_2那么它将从sub_id的基础上的Color元素中删除。

我尝试了下面的解决方案。但是,它不起作用:

$.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

javascript jquery knockout.js
2个回答
0
投票

以下片段从customOptionVal observableArray本身删除 -

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

但是,如果您只想从Color数组(不是observableArray)中删除,请使用以下代码段 -

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


0
投票

我找到了更好的方法:

如屏幕截图所示,创建一个ko observable数组并在该ko.observableArray中设置Color值

custom_option_select_text_arr = ko.observableArray([])
.....
this.custom_option_select_text_arr.push({sub_color: "Red", sub_id: "options_3_2", is_checked: true});
this.customOptionVal()['Color'] = this.custom_option_select_text_arr();

现在,对于删除元素:

self.custom_option_select_text_arr.remove(self.custom_option_select_text_arr()[0]);
self.customOptionVal()['Color'] = this.custom_option_select_text_arr();
© www.soinside.com 2019 - 2024. All rights reserved.