Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a specific object from an immutable js map by value?

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(); 
like image 596
sspross Avatar asked Mar 18 '15 13:03

sspross


People also ask

Is .MAP immutable?

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.

Is JavaScript map immutable?

js provides many Persistent Immutable data structures including: List , Stack , Map , OrderedMap , Set , OrderedSet and Record .

What is ImmutableJS?

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 .


2 Answers

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;}); 
like image 127
blgt Avatar answered Sep 23 '22 21:09

blgt


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'} 
like image 45
Joshua Avatar answered Sep 19 '22 21:09

Joshua