xiankai xiankai - 1 year ago 122
Javascript Question

Getting nested values in Immutable.js

According to the docs here: https://facebook.github.io/immutable-js/docs/#/Map/getIn

I should be able to get the deeply nested value by providing an array for the

argument. This is what I've done, however I'm getting
as the return value.


var obj = Immutable.Map({categories: {1: 'a', 2: 'b'}});
var output = obj.getIn(['categories', 1]);

What am I doing wrong?

Answer Source

A map is simply a collection of keys with values. What you have is a map with the key "categories", and the value "{1: 'a', 2: 'b'}". The value does not automatically become an Immutable map just because you place it inside another map.

Now, the getIn() function will only "see" other Immutable.js maps. What you have in there is a regular ol' javascript object. If you just want to get the "1" value, you can just do:


If you want the "categories" collection to also be a map, you'll have to define that explicitly. Also, as Amit pointed out, you'll need to use strings with the getIn() function.

var obj = Immutable.Map({
	categories: Immutable.Map({
		1: 'a',
		2: 'b'
var output = obj.getIn(['categories', '1']);

The above code will return "a".

It would probably be more convenient for you to do something like below, if you have many nested maps.

var obj = Immutable.fromJS({
	categories: {
		1: 'a',
		2: 'b'

The fromJs() function will convert any nested objects into maps or lists automatically for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download