Reputation: 6125
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/
Upvotes: 26
Views: 29515
Reputation: 521
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" ]
Upvotes: 1
Reputation: 1807
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
Upvotes: 3
Reputation: 7575
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();
Upvotes: 48
Reputation: 915
This is how ImmutableJS object looks like.
If you want to get:
["firstKey", "secondKey"]
You need to do:
console.log(map.keySeq().toArray())
Upvotes: 39