Search code examples
typescriptimmutable.js

Immutable.js difference between toJSON() and toObject() on Record


With the release of Immutable v4, there has been some api changes.

toJS(): any became toJS(): {[key: string]: unknown}

From what I understand it has been replaced by toJSON() but what's the difference with toObject() ? The documentation isn't very clear on that topic.

toJSON(): TProps
   Shallowly converts this Record to equivalent native JavaScript Object.

toObject(): TProps
   Shallowly converts this Record to equivalent JavaScript Object.

Solution

  • The names can be taken literally:

    toObject creates javascript plain objects, while toJSON chooses the datatype based on the collection type.

    For keyed collections (Record, Map, OrderedMap), toJSON and toObject do the same.

    However, for list types (Lists, Set, OrderedSet) there is a difference: toJSON returns an Array, while toObject generates an Object where the keys are the indexes:

    List(['a','b']).toJSON()   // ['a', 'b']
    List(['a','b']).toObject() // { "1": "a", "2": "b" }