如何获得两个不变地图之间的差异?

时间:2019-04-04 13:52:31

标签: javascript frontend immutability

我有两个不变的地图:

const first = immutable.Map({ one: 1, two: 2 });
const two = immutable.Map({ one: 1, two: 2, three: 3 });

如何获得差异? 我应该得到:

{ three: 3 } // Map because need merge this data in the feature

1 个答案:

答案 0 :(得分:0)

在不可变的4.0.0-rc.12中,您可以做到

const first = Immutable.Map({ one: 1, two: 2 });
const two = Immutable.Map({ one: 1, two: 2, three: 3 });
console.log(two.deleteAll(first.keys()).toJS())

达到相似的结果 deleteAll在版本3中不是问题,因此我想您可以从map键生成集合并将它们相交

const m1 = new Immutable.Map({foo: 2, bar: 42});
const m2 = new Immutable.Map({foo: 2, bar: 42, buz: 44});


const s1 = Immutable.Set(m1.keys());
const s2 = Immutable.Set(m2.keys());

const s3 = s2.subtract(s1);
const tmp = {};
for (let key of s3.keys()) {
  tmp[key] = m2.get(key);
}

const res = new Immutable.Map(tmp);
console.log(res.toJS());