26

I want to retrieve keys() from the following Immutable Map:

var map = Immutable.fromJS({"firstKey": null, "secondKey": null });
console.log(JSON.stringify(map.keys()));

I would expect the output:

["firstKey", "secondKey"]

However this outputs:

{"_type":0,"_stack":{"node":{"ownerID":{},"entries":[["firstKey",null],["secondKey",null]]},"index":0}}

How to do it properly?

JSFiddle link: https://jsfiddle.net/o04btr3j/57/

knagode
  • 5,816
  • 5
  • 49
  • 65

4 Answers4

48

Although this question got answered a while ago, here is a little update:

ES6 Solution:

const [ ...keys ] = map.keys();

Pre ES6 Solution:

var keys = map.keySeq().toArray();
lumio
  • 7,428
  • 4
  • 40
  • 56
39

This is how ImmutableJS object looks like.

If you want to get:

["firstKey", "secondKey"]

You need to do:

console.log(map.keySeq().toArray())
Sagi Medina
  • 915
  • 1
  • 9
  • 11
  • 3
    You can also use the generic `toJS()` to convert immutable types back to normal js objects or arrays. – OlliM Feb 25 '16 at 15:48
3

Possibly just answering my own question that lead me here, but I found mapKeys() which will gives you access to keys in a regular loop. It seems a bit more "the right way". (The docs are so vague, who knows!)

eg:

Map({ a: 1, b: 2 }).mapKeys((key, value) => console.log(key, value))
// a 1
// b 2
atomictom
  • 1,637
  • 16
  • 14
0

Best practice with Immutable.js is to use Immutable data structures and minimize conversions to JavaScript types. For this problem we can use keySeq(), which returns a new Seq.Indexed (an ordered indexed list of values) of the keys of this Map. We then can then set a List to those values and assign that List to a variable for use later. Here is an example of how this solution could be implemented:

import { Map, List } from 'immutable';

const exampleMap = Map({ a: 10, b: 20, c: 30 });

const keys = List(exampleMap.keySeq()); // List [ "a", "b", "c" ]
josephemswiler
  • 401
  • 4
  • 5