javascript 从 Immutable.js 中 Map 内的 List 中删除元素的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29851147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to remove an element from a List inside of a Map in Immutable.js
提问by Matthew Herbst
I am using Facebook's Immutable.jsto 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?
我正在使用Facebook 的 Immutable.js来加速我的 React 应用程序以利用PureRender mixin。我的数据结构之一是 aMap()
并且该映射中的键之一将 aList<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]);
}
(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.)
(我已经考虑将 theList<Map>()
移到 aMap()
本身,因为列表中的每个元素都有一个 UUID,但是,我还没有到那个时候。)
回答by OlliM
You could use Map.filter
:
你可以使用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.
从性能的角度来看,切换到 Map 可能会更有效,因为此代码(如您的代码)必须遍历列表中的元素。
回答by quotesBro
Using updateInas suggested by @YakirNa this will look like below.
按照@YakirNa 的建议使用updateIn这将如下所示。
ES6:
ES6:
onRemoveMetric(graphId, metricUUID) {
this.graphs = this.graphs.updateIn([graphId, 'metrics'],
(metrics) => metrics.filter(
(metric) => metric.get('uuid') !== metricUUID
)
);
}
ES5:
ES5:
onRemoveMetric: function(graphId, metricUUID) {
this.graphs = this.graphs.updateIn([graphId, "metrics"], function(metrics) {
return metrics.filter(function(metric) {
return metric.get("uuid") !== metricUUID;
});
});
}