How do I get a specific object from an immutable js map by value?
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); // falseImmutable.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 anywayvar 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'}
It may be important to guarantee the order of the array. If that's the case:
- Use an OrderedMap
- Do a set method on the OrderedMap at each iteration of your source array
The example below uses "withMutations" for better performance.
var OrderedMap = Immutable.OrderedMap// Get new OrderedMapfunction getOm(arr) { return OrderedMap().withMutations(map => { arr.forEach(item => map.set(item.id, item)) })}// Source collectionvar srcArray = [ { id: 123, value: 'foo' }, { id: 456, value: 'bar' }]var myOrderedMap = getOm(srcArray)myOrderedMap.get(123)// --> { id: 123, value: 'foo' }myOrderedMap.toObject()// --> { 123: {id: 123, value: 'foo'}, 456: {id: 456, value: 'bar'} }myOrderedMap.toArray()// --> [ {id: 123, value: 'foo'}, { id: 456, value: 'bar' } ]