immutable.js get keys from map/hash
Asked Answered
C

4

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/

Calamus answered 25/2, 2016 at 9:33 Comment(0)
D
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();
Dagan answered 3/4, 2017 at 18:16 Comment(2)
ES6 is ES2015. Do you mean pre-ES2015?Sheepdip
Changed. Thanks for mentioningDagan
P
39

This is how ImmutableJS object looks like.

If you want to get:

["firstKey", "secondKey"]

You need to do:

console.log(map.keySeq().toArray())
Pressor answered 25/2, 2016 at 11:51 Comment(1)
You can also use the generic toJS() to convert immutable types back to normal js objects or arrays.Iodoform
P
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
Preoccupation answered 5/9, 2018 at 9:11 Comment(0)
S
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" ]
Slavonic answered 10/5, 2019 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.