I created an immutable map (with Immutable-JS) from a list of objects:
var result = [{'id': 2}, {'id': 4}]; var map = Immutable.fromJS(result);
Now i want to get the object with id = 4
.
Is there an easier way than this:
var object = map.filter(function(obj){ return obj.get('id') === 4 }).first();
ImmutableMap, as suggested by the name, is a type of Map which is immutable. It means that the content of the map are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the Map, UnsupportedOperationException is thrown.
js provides many Persistent Immutable data structures including: List , Stack , Map , OrderedMap , Set , OrderedSet and Record .
Immutable. js is a library that supports an immutable data structure. It means that once created data cannot be changed. It makes maintaining immutable data structures easier and more efficient. The tool supports data structure like: List, Map, Set and also structures that are not implemented in .
Essentially, no: you're performing a list lookup by value, not by index, so it will always be a linear traversal.
An improvement would be to use find
instead of filter
:
var result = map.find(function(obj){return obj.get('id') === 4;});
The first thing to note is that you're not actually creating a map, you're creating a list:
var result = [{'id': 2}, {'id': 4}]; var map = Immutable.fromJS(result); Immutable.Map.isMap(map); // false Immutable.List.isList(map); // true
In order to create a map you can use a reviver
argument in your toJS
call (docs), but it's certainly not the most intuitive api, alternatively you can do something like:
// lets use letters rather than numbers as numbers get coerced to strings anyway var result = [{'id': 'a'}, {'id': 'b'}]; var map = Immutable.Map(result.reduce(function(previous, current) { previous[ current.id ] = current; return previous; }, {})); Immutable.Map.isMap(map); // true
Now we have a proper Immutable.js map which has a get method
var item = Map.get('a'); // {id: 'a'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With