How to update element inside List with ImmutableJS?

后端 未结 7 1154
面向向阳花
面向向阳花 2020-12-04 09:02

Here is what official docs said

updateIn(keyPath: Array, updater: (value: any) => any): List
updateIn(keyPath: Array, notSe         


        
7条回答
  •  眼角桃花
    2020-12-04 09:25

    Use .map()

    list = list.map(item => 
       item.get("name") === "third" ? item.set("count", 4) : item
    );
    

    var arr = [];
    arr.push({id: 1, name: "first", count: 2});
    arr.push({id: 2, name: "second", count: 1});
    arr.push({id: 3, name: "third", count: 2});
    arr.push({id: 4, name: "fourth", count: 1});
    var list = Immutable.fromJS(arr);
    
    var newList = list.map(function(item) {
        if(item.get("name") === "third") {
          return item.set("count", 4);
        } else {
          return item;
        }
    });
    
    console.log('newList', newList.toJS());
    
    // More succinctly, using ES2015:
    var newList2 = list.map(item => 
        item.get("name") === "third" ? item.set("count", 4) : item
    );
    
    console.log('newList2', newList2.toJS());

提交回复
热议问题