Skip to content

Converting from JS objects

Andrew Couch edited this page Feb 22, 2016 · 8 revisions

Often we need to convert plain JavaScript Objects and Arrays into Immutable collections. There are a few ways to do this:

Type Constructors

Immutable collections can be constructed from plain JavaScript objects and arrays.

For example, we can create an Immutable.Map from a plain JavaScript object.

var map = new Map({key1: "value1", key2: "value2"});

Since Map keys can be complex, not just strings, we can also construct an Immutable.Map from an array of entries.

var map = new Map([["key1", "value1"], ["key2", "value2"]]);

It's important to keep in mind that type constructors convert the provided Object or Array shallowly. This ensures that no assumptions are made about the contents of your collections.

If you are converting deeply nested JavaScript Objects and Arrays, you need something more.

Converting nested data

The convenience function Immutable.fromJS() will convert nested Objects and Arrays to Immutable.Map and Immutable.List, respectively.

var imm = Immutable.fromJS({ list: [ { k: "v" }, { k: { x: 3, y: 5 } } ] } );

Immutable.fromJS() is conservative in its conversion. It only converts plain Objects (no custom prototype) to Immutable.Map and true Arrays to Immutable.List. This ensures that exotic objects (Date objects, DOM nodes, user-defined types) don't get converted to Immutable.Map unintentionally.

Custom conversion

The implementation of fromJS is quite simple, so making your own version with semantics custom to your environment will result in a fairly small utility function.

Here is an example which will convert any Object, including exotic Objects, to Immutable.Map:

function fromJSGreedy(js) {
  return typeof js !== 'object' || js === null ? js :
    Array.isArray(js) ? 
      Immutable.Seq(js).map(fromJSGreedy).toList() :
      Immutable.Seq(js).map(fromJSGreedy).toMap();
}

Or here is a version which turns JS objects into Immutable.OrderedMap:

function fromJSOrdered(js) {
  return typeof js !== 'object' || js === null ? js :
    Array.isArray(js) ? 
      Immutable.Seq(js).map(fromJSOrdered).toList() :
      Immutable.Seq(js).map(fromJSOrdered).toOrderedMap();
}