Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

309
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda