使用ImmutableJS更新地图列表中的一个键

问题描述 投票:1回答:2

immutable.js的文档,缺少描述性示例。有人可以解释一下,如何在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;
})

非常感谢您的帮助。

javascript immutability immutable.js
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'))))

检查此笔的控制台输出:http://codepen.io/anon/pen/Nxzdwe?editors=1012


0
投票

所以这是我的版本:

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()
);
© www.soinside.com 2019 - 2024. All rights reserved.