Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork1.8k
Converting from JS objects
Often we need to convert plain JavaScript Objects and Arrays intoImmutable collections. There are a few ways to do this:
Immutable collections can be constructed from plain JavaScript objects and arrays.
For example, we can create anImmutable.Map from a plain JavaScript object.
varmap=newMap({key1:"value1",key2:"value2"});
Since Map keys can be complex, not just strings, we can also construct anImmutable.Map from an array of entries.
varmap=newMap([["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.
The convenience functionImmutable.fromJS() will convert nested Objects and Arrays toImmutable.Map andImmutable.List, respectively.
varimm=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) toImmutable.Map and true Arrays toImmutable.List. This ensures that exotic objects (Date objects, DOM nodes, user-defined types) don't get converted toImmutable.Map unintentionally.
The implementation offromJS 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, toImmutable.Map:
functionfromJSGreedy(js){returntypeofjs!=='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 intoImmutable.OrderedMap:
functionfromJSOrdered(js){returntypeofjs!=='object'||js===null ?js :Array.isArray(js) ?Immutable.Seq(js).map(fromJSOrdered).toList() :Immutable.Seq(js).map(fromJSOrdered).toOrderedMap();}