1

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.

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

2 Comments

Almost but not. It will return only array of changed values but i want whole collection This answer gave me some ideas with .map
Didn't realise that was what you wanted, have updated with my suggestion. See the updated codepen
0

So here is my version:

const collection = Immutable.fromJS([{a: 1, b: 2}, {a: 3, b: 7}, {a: 5, b: 6}]);

console.log(
  collection    
    .map(item => {
      if (item.get('b') % 2 == 0) {
        return item.set('a', item.get('a') * 2)
      } else {
        return item;
      }
    }).toJS()
);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.