Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

310
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda