fromJS()

Deeply converts plain JS objects and arrays to Immutable Maps and Lists.

fromJS(jsValue: unknown,reviver?: (key: string | number,sequence: Collection.Keyed<string, unknown> | Collection.Indexed<unknown>,path?: Array<string | number>) => unknown): Collection<unknown, unknown>

Discussion

fromJS will convert Arrays and array-like objects to a List, and plain objects (without a custom prototype) to a Map. Iterable objects may be converted to List, Map, or Set.

If a reviver is optionally provided, it will be called with every collection as a Seq (beginning with the most nested collections and proceeding to the top-level collection itself), along with the key referring to each collection and the parent JS object provided as this. For the top level, object, the key will be "". This reviver is expected to return a new Immutable Collection, allowing for custom conversions from deep JS objects. Finally, a path is provided which is the sequence of keys to this value from the starting value.

reviver acts similarly to the same parameter in JSON.parse.

If reviver is not provided, the default behavior will convert Objects into Maps and Arrays into Lists like so:

const { fromJS, isKeyed } = require('immutable')
function (key, value) {
  return isKeyed(value) ? value.toMap() : value.toList()
}run it

Accordingly, this example converts native JS data to OrderedMap and List:

const { fromJS, isKeyed } = require('immutable')
fromJS({ a: {b: [10, 20, 30]}, c: 40}, function (key, value, path) {
  console.log(key, value, path)
  return isKeyed(value) ? value.toOrderedMap() : value.toList()
})

> "b", [ 10, 20, 30 ], [ "a", "b" ]
> "a", {b: [10, 20, 30]}, [ "a" ]
> "", {a: {b: [10, 20, 30]}, c: 40}, []run it

Keep in mind, when using JS objects to construct Immutable Maps, that JavaScript Object properties are always strings, even if written in a quote-less shorthand, while Immutable Maps accept keys of any type.

const { Map } = require('immutable')
let obj = { 1: "one" };
Object.keys(obj); // [ "1" ]
assert.equal(obj["1"], obj[1]); // "one" === "one"

let map = Map(obj);
assert.notEqual(map.get("1"), map.get(1)); // "one" !== undefinedrun it

Property access for JavaScript Objects first converts the key to a string, but since Immutable Map keys can be of any type the argument to get() is not altered.

This documentation is generated from immutable.d.ts. Pull requests and Issues welcome.

© 2014–present, Lee Byron and other contributors
Licensed under the 3-clause BSD License.
https://immutable-js.com/docs/v4.0.0/fromJS()/