Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ImmutableJS Map() and fromJS()?

var a = {address: {postcode: 5085}}  var b = Immutable.fromJS(a) var c = b.setIn(['address', 'suburb'], 'broadview').toJS(); // no error console.log(c);   var d = Immutable.Map(a); var e = d.setIn(['address', 'suburb'], 'broadview').toJS(); // error invalid keyPath(…) 

Could someone explain the difference.

Thanks,

like image 847
sowdri Avatar asked Oct 23 '15 23:10

sowdri


People also ask

What does fromJS do?

fromJS is a useful function that converts nested data into Immutable. It creates Maps and Lists in the conversion.

Is Map Immutable js?

js provides many Persistent Immutable data structures including: List , Stack , Map , OrderedMap , Set , OrderedSet and Record .

What is Immutable fromJS?

Immutable. js offers the fromJS() method to build immutable structures from objects and array. Objects are converted into maps. Arrays are converted into lists. The fromJS() method can also take a reviver function for custom conversions.

What is toJS?

toJS() converts plain JS objects with a length property, in an Immutable collection, to an array (v4) #1438.


1 Answers

In this example,

var a = {address: {postcode: 5085}} var d = Immutable.Map(a); 

Here, d.get('address') is immutable. It's value cannot change to any other objects. We can only create a new Object from the existing object using the Immutable.Map.set() function of ImmutableJS.

But, the object referenced by d.get('address') i.e, {postcode:5085} is a standard JavaScript object. It is mutable. A statement like this can alter the value of postcode:

d.get('address').postcode=6000; 

If you check the value of d again, you can see that he value has been changed.

console.log(JSON.stringify(d));   //Outputs {"address":{"postcode":6000}} 

which is against the principles of immutability.

The reason is that ImmutableJS data structures like List and Map imparts the immutability feature to only the level-1 members of the List/Map.

So, if you have objects inside arrays or arrays inside objects and want them too to be immutable, your choice is Immutable.fromJS.

var a = {address: {postcode: 5085}} var b = Immutable.fromJS(a); b.get('address').postcode=6000; console.log(JSON.stringify(b));   //Outputs {"address":{"postcode":5085}} 

From the above example you can clearly know how fromJS makes the nested members immutable.

I hope you understood the difference between Map and fromJS. All the best =)

like image 73
Samu Avatar answered Oct 08 '22 03:10

Samu