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]);
}
});
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
I found better way that :
As see in screenshot, create one ko observable array and set Color value in that ko.observableArray
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();
Now, for remove element :
self.custom_option_select_text_arr.remove(self.custom_option_select_text_arr()[0]);
self.customOptionVal()['Color'] = this.custom_option_select_text_arr();