Merging maps by key

When merging maps, there's always the chance that keys will conflict. The question is, which value gets used? Let's illustrate this idea by merging two simple lists together:

const myMap1 = Map.of(
'one', 1, 'two', 2, 'three', 3
);
const myMap2 = Map.of(
'two', 22, 'three', 33, 'four', 4
);
const myMergedMap = myMap1.merge(myMap2);

console.log('myMap1', myMap1.toJS());
// -> myMap1 { one: 1, two: 2, three: 3 }
console.log('myMap2', myMap2.toJS());
// -> myMap2 { two: 22, three: 33, four: 4 }
console.log('myMergedMap', myMergedMap.toJS());
// -> myMergedMap { one: 1, two: 22, three: 33, four: 4 }

As you can see, myMergedMap contains every key from myMap1 and myMap2. There are two conflicting keys—two and three. By default, the merge() method will just override existing values. If you want to change this behavior, you have to use the mergeWith() method:

const myMergedWithMap = myMap1.mergeWith(
v => v,
myMap2
);

console.log('myMergedWithMap', myMergedWithMap.toJS());
// -> myMergedWithMap { one: 1, two: 2, three: 3, four: 4 }

The first argument that's passed to mergeWith() is a function that returns the value to use in case of a conflict. The function is passed to the two values of the conflicting key and the key itself as a third argument. In our case, we just want to use the old value when there's a conflict, so we just return the first argument.

Other approaches to merging objects, such as Object.assign(), will actually mutate the first argument. To avoid this, you'll see empty objects passed as the first argument. Things like this aren't a concern in Immutable.js because any mutative method returns a new collection.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.15.248