Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

javascript - 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,

question from:https://stackoverflow.com/questions/33312922/what-is-the-difference-between-immutablejs-map-and-fromjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 =)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...