Search code examples
javascriptimmutabilityimmutable.js

Updating one key in list of maps using ImmutableJS


Docs for immutable.js, lack descriptive examples. Could somebody kindly explain, how I could perform the following in ImmutableJS:

function isOdd (v) {
    return v % 2 === 0
}

var collection = [{a: 1, b: 2}, {a: 3, b: 7}, {a: 5, b: 6}];
collection.map(item => {
 if (isOdd(item.b))  {
   item.a = item.a * 2;
 }
 return item;
})

Any help is highly appreciated.


Solution

  • const collection = Immutable.fromJS([{a: 1, b: 2}, {a: 3, b: 7}, {a: 5, b: 6}]);
    
    const isOdd = a => b => b % 2 ? a : a * 2;  
    
    collection
      .map(item => item
          .update('a', a => isOdd(a)(item.get('b'))))
    

    Check the console output of this pen: http://codepen.io/anon/pen/Nxzdwe?editors=1012