在 Immutable.js 中从 Map 内的 List 中删除元素的最佳方法

Best way to remove an element from a List inside of a Map in Immutable.js

我正在使用 Facebook's Immutable.js to speed up my React application to take advantage of the PureRender mixin。我的数据结构之一是 Map(),并且该映射中的一个键的值是 List<Map>()。我想知道的是,不知道要从 List() 中删除的项目的索引,删除它的最佳方法是什么?到目前为止,我已经想出了以下内容。这是最好(最有效)的方法吗?

// this.graphs is a Map() which contains a List<Map>() under the key "metrics"
onRemoveMetric: function(graphId, metricUUID) {
    var index = this.graphs.getIn([graphId, "metrics"]).findIndex(function(metric) {
        return metric.get("uuid") === metricUUID;
    });
    this.graphs = this.graphs.deleteIn([graphdId, "metrics", index]);
}

(我考虑过将 List<Map>() 移动到 Map() 本身,因为列表中的每个元素都有一个 UUID,但是,我还没有到那个时候。)

您可以使用 Map.filter:

onRemoveMetric: function(graphId, metricUUID) {
  this.graphs = this.graphs.setIn([graphId, "metrics"],
    this.graphs.getIn([graphId, "metrics"]).filter(function(metric) {
      return metric.get("uuid") !== metricUUID;
    })
  )
}

从性能的角度来看,切换到 Map 可能会更有效,因为此代码(如您的代码)必须遍历列表中的元素。

按照@YakirNa 的建议使用updateIn,这将如下所示。

ES6:

  onRemoveMetric(graphId, metricUUID) {
    this.graphs = this.graphs.updateIn([graphId, 'metrics'],
      (metrics) => metrics.filter(
        (metric) => metric.get('uuid') !== metricUUID
      )
    );
  }

ES5:

  onRemoveMetric: function(graphId, metricUUID) {
    this.graphs = this.graphs.updateIn([graphId, "metrics"], function(metrics) {
      return metrics.filter(function(metric) {
        return metric.get("uuid") !== metricUUID;
      });
    });
  }