Immutable JS compare nested structures(不可变 JS 比较嵌套结构)
问题描述
我有 2 个嵌套结构 newState 和 newState1.
I have 2 nested structures newState and newState1.
但是当我比较它们时,equals() 或 Immutable.is() 返回 false.这些结构中的值相同.
But when I compare their, equals() or Immutable.is() returned false. The values in these structures identical.
如何正确比较newState和newState1?
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
JSFiddle 中的代码:https://jsfiddle.net/z3xuagwm/
Code in JSFiddle: https://jsfiddle.net/z3xuagwm/
推荐答案
好像immutablejs不做深度转换,所以如果你的value是object,就一直是object.
It seems that immutablejs don't do deep conversion, so if your value is object, it stays to be object.
由于您在每个更新步骤中创建不同的对象,并且当您相互比较时,这些对象将被视为不同,因此您还应该将其转换为 Immutable.Map 对象,以使比较为真.
As you're creating different object in each update step, and those objects will be treat different when you compare to each other, so you should also convert it to Immutable.Map object, to make the compare be 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>
这篇关于不可变 JS 比较嵌套结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不可变 JS 比较嵌套结构
基础教程推荐
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 动态更新多个选择框 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01