Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
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();
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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;});
over 4 years ago · Santiago Trujillo Report

0

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'}
over 4 years ago · Santiago Trujillo Report

0

When using fromJS for array, you'll get List not map. It will be better and easier if you create a map. The following code will convert the result into Immutable map.

  const map = result.reduce((map, json) =>
    map.set(json.id, Immutable.fromJS(json))
  , Map());

Now, you can

   map.get('2');   //{'id': 2}

Note, if the result has nested structure and if that has array, it will be a List with the above code.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!