Immutable JS compare nested structures

I have two nested structures newState and newState1 .

But when I compare them, equals () or Immutable.is () returns false . The values ​​in these structures are identical.

How to compare newState and newState1 correctly ?

var grid = { editable: false, widgets: [{ name: 'Some widget', type: 'List', defaultDataSource: 'daily', dataSources: {} }, { name: 'Some widget1', type: 'List', defaultDataSource: 'daily', dataSources: {} }] }; var state = Immutable.fromJS(grid); var newState = state.updateIn(['widgets'], function (list) { return list.push(Immutable.Map({ name: 'Some widget2', type: 'List', defaultDataSource: 'daily', dataSources: {} })); }); var newState1 = state.updateIn(['widgets'], function (list) { return list.push(Immutable.Map({ name: 'Some widget2', type: 'List', defaultDataSource: 'daily', dataSources: {} })); }); console.log(state.toJS(), newState.toJS(), newState1.toJS()); console.log(newState.equals(newState1)); //false 

Code in JSFiddle: https://jsfiddle.net/z3xuagwm/

+7
javascript compare
source share
3 answers

It seems that immutablejs does not perform deep conversion, so if your value is an object, it remains an object.

How do you create another object at each stage of updating, and these objects will relate to another when you compare with each other, so you also need to convert it to an Immutable.Map object so that the comparison is true.

 // Primitives. var test1 = Immutable.Map({ a: 'a', b: 'b', c: 'c' }); var test2 = Immutable.Map({ a: 'a', b: 'b', c: 'c' }); console.log('Test primitive', test1.equals(test2)); // true // Object test1 = Immutable.Map({ a: 'a', b: 'b', c: {} }); test2 = Immutable.Map({ a: 'a', b: 'b', c: {} }); console.log('Test object', test1.equals(test2)); // false // Its because var a = {}; var b = {}; console.log('a === b?', a === b); // false // Convert test1 = Immutable.Map({ a: 'a', b: 'b', c: Immutable.Map({}) }); test2 = Immutable.Map({ a: 'a', b: 'b', c: Immutable.Map({}) }); console.log('Test converted', test1.equals(test2)); // true 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.5/immutable.min.js"></script> 
+15
source share

Change Immutable.Map to Immutable.fromJS in your push functions (as already mentioned - only JS will do deep conversion, Map, List, etc.):

 var newState = state.updateIn(['widgets'], function (list) { return list.push(Immutable.fromJS({ name: 'Some widget2', type: 'List', defaultDataSource: 'daily', dataSources: {} })); }); var newState1 = state.updateIn(['widgets'], function (list) { return list.push(Immutable.fromJS({ name: 'Some widget2', type: 'List', defaultDataSource: 'daily', dataSources: {} })); }); 
+8
source share

How about using JSON.stringify ?

 JSON.stringify(values) !== JSON.stringify(anothervalue); 

If you know that they are not round objects and do not contain functions, I believe that this is the fastest way to compare them.

0
source share

All Articles