3

I'm trying to merge 2 immutable maps as below, using mergeDeep() of Immutable.js

import { expect } from 'chai';
import Immutable from 'immutable';
describe.only('Test', () => {
    it('should return correct merged objects', () => {
        const current = Immutable.Map({
            a: [],
            b: {},
            c: {
                'c01': {
                    key: 'c01'
                }
            }
        });
        const next = {
            a: [],
            b: {},
            c: {
                'c01': {
                    key: 'c01'
                },
                'c02': {
                    key: 'c02'
                }
            }
        };
        const newObj = Immutable.Map({
            a: [],
            b: {},
            c: {
                'c02': {
                    key: 'c02'
                }
            }
        });
        expect(current.mergeDeep(newObj).toJSON()).to.deep.equal(next);
    });
});

However, the property 'c01' is missing after merging.

 AssertionError: expected { Object (a, b, ...) } to deeply equal { Object (a, b, ...) }
      + expected - actual

       {
         "a": []
         "b": {}
         "c": {
      +    "c01": {
      +      "key": "c01"
      +    }
           "c02": {
             "key": "c02"
           }
         }

Can mergeDeep() do the merging for different properties from 2 different Map objects or only merge properties which are mutual in both? If it can't, how can I get the expected merged object as above?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
CygnusKnight
  • 87
  • 1
  • 13

1 Answers1

4

change

const current = Immutable.Map({ ... });

to

const current = Immutable.fromJS({ ... });
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
Todd Moore
  • 420
  • 2
  • 7
  • 2
    Thanks, you are right. `fromJS` does a deeper conversion from plain JS objects and arrays to Immutable Maps and Lists. – CygnusKnight Jan 05 '16 at 23:13
  • Check the console output from this codepen, the issue is not with `Immutable` http://codepen.io/toddmoorega/pen/xZqqNM?editors=001 – Todd Moore Jan 05 '16 at 23:15
  • The issue is my mistake to go for wrong function. It should have been `fromJS` instead of `Map` constructor because `fromJS` does recursive conversion for the whole tree. Your answer above is absolutely what I need and it solves the issue. – CygnusKnight Jan 06 '16 at 02:36