【问题标题】:Knockout : Remove array element by specific field value淘汰赛:通过特定字段值删除数组元素
【发布时间】:2019-01-23 19:56:40
【问题描述】:

我想通过特定的字段值删除 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 元素 中删除。 p>

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

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

【问题讨论】:

  • 您要完全删除 Color 元素还是具有该颜色元素的 Option?我问这个是因为您要从可观察数组中删除 self.customOptionVal
  • 这对我不起作用。
  • 如果customOptionVal observableArray,您如何访问self.customOptionVal()['Color']?我假设您正在使用键 ColorSize 将对象设置为 ko.observableArray()。应该改为ko.observable()

标签: javascript jquery knockout.js


【解决方案1】:

以下 sn-p 从customOptionVal observableArray 本身中删除 -

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

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

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

【讨论】:

  • 你能告诉我其他方式吗? ko.utils.arrayForEach 不工作,
  • 是否可以对我的代码进行一些修改并获得输出?
  • 我看不出ko.utils.arrayForEach对你不起作用的任何原因......我已经更新了解决方案......现在它使用vanilla js而不是淘汰赛进行迭代......小提琴也更新了
  • 仍然无法正常工作。我添加了图像。我在 Magento 做。这个控制台是关于 self.customOptionVal() 的。可以看到Color中有custom_option_id。我想在 custom_option_id 的基础上删除。点击后,我可以获得 custom_option_id 的值。
  • 我怎样才能获得 0 索引所有值。我使用了 self.customOptionVal()['Color'][0] 。但是,它不起作用。
【解决方案2】:

我找到了更好的方法:

如屏幕截图所示,创建一个 ko 可观察数组并在该 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 2015-05-28
    • 1970-01-01
    • 2016-03-15
    • 2017-12-13
    相关资源
    最近更新 更多