Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Converting from JS objects

Andrew Couch edited this pageFeb 22, 2016 ·8 revisions

Often we need to convert plain JavaScript Objects and Arrays intoImmutable 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 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.

Converting nested data

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.

Custom conversion

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();}
Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp