Search code examples
javascriptimmutable.js

Immutable JS - converting a collection of Maps to a List


I have the following structure in the project im working on (uses immutable JS):

data :[{name: 'john', surname: 'smith', children: [{name: 'sam'}, {name: 'ben'}]},
       {name: 'jane', surname: 'jones', children: [{name: 'tim'}, {name: 'amy'}]}]

the object is converted to immutable JS via fromJS().

I need a new object in the following structure:

data :[{name: 'john', surname: 'smith', children: ['sam','ben']},
       {name: 'jane', surname: 'jones', children: ['tim','amy']}]

Any pointers much appreciated.


Solution

  • The pure JS answer of Christian doesn't exactly apply to immutable.js objects, so here are a few ways to do it with immutable.js's collection API.

    There are more options (e.g. reduce), feel free to check the docs; the method descriptions usually come with examples.

    const raw = [{name: 'john', surname: 'smith', children: [{name: 'sam'}, {name: 'ben'}]},
           {name: 'jane', surname: 'jones', children: [{name: 'tim'}, {name: 'amy'}]}];
    
    const data = Immutable.fromJS(raw);
    
    function run(name, operation) {
      let result;
      console.time(name);
      for(let i=0; i < 50000; i++){
        result = operation();
      }
      console.timeEnd(name);
      console.log(result1.toJS());
    }
    
    
    run('simple', () => {
      // simply updating objects inside a mapping
      result1 = data.map(
        person => person.update('children',
          kidObjs => kidObjs.map(
            kid => kid.get('name')
          )
        )
      );
    });
    
    
    run('withMutations and setIn', () => {
      // using withMutations and setIn
      result2 = data.withMutations(list => {
        list.forEach((val, idx) => {
          list.setIn(
            [idx, 'children'],
            val.get('children').map(kid => kid.get('name'))
          )
        });
      });
    });
    
    run('withMutations and update', () => {
      // slightly faster by using withMutations set/update
      result2 = data.withMutations(list => {
        list.forEach((val, idx) => {
          list.set(idx, val.update('children', kids => kids.map(kid => kid.get('name'))))
        });
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.14/immutable.min.js"></script>