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

天大地大妈咪最大 提交于 2019-12-10 03:16:59

问题


I am using Facebook's Immutable.js to speed up my React application to take advantage of the PureRender mixin. One of my data structures is a Map() and one of the keys in that map has a List<Map>() as its value. What I'm wondering is, not knowing the index of the item I want to remove from the List(), what is the best way to go about removing it? So far I have come up with the below. Is this the best (most efficient) way?

// 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]);
}

(I have considered moving the List<Map>() to a Map() itself since each element in the list has a UUID, however, I'm not at that point yet.)


回答1:


You could use 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;
    })
  )
}

From a performance point of view switching to a Map would probably be more efficient, as this code (like yours) has to iterate over the elements in the list.




回答2:


Using updateIn as suggested by @YakirNa this will look like below.

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;
      });
    });
  }


来源:https://stackoverflow.com/questions/29851147/best-way-to-remove-an-element-from-a-list-inside-of-a-map-in-immutable-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!