如何使用ImmutableJS更新List内的元素? [英] How to update element inside List with ImmutableJS?

查看:880
本文介绍了如何使用ImmutableJS更新List内的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

官方文档说:

  updateIn(keyPath:Array< any> updater:(value:any)= >任何):列表< T> 
updateIn(keyPath:Array< any> ;, notSetValue:any,updater:(value:any)=> any):List< T>
updateIn(keyPath:Iterable< any,any>,updater:(value:any)=> any):List< T>
updateIn(keyPath:Iterable< any,any> notSetValue:any,updater:(value:any)=> any):List< T>

正常的web开发人员(不是功能程序员)不会理解这一点!

我非常简单(对于非功能性方法)的情况。

  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.List.of(arr);

如何更新 list where element with名称第三将其 count 设置为 4 div>

最适合的情况是同时使用 findIndex 更新方法。

  list = list.update(
list.findIndex(function(item){
return item.get(name)) ===third;
}),function(item){
return item.set(count,4);
}
);

使用地图并不总是可能的。例如。如果名称不是唯一的,我想更新所有具有相同名称的项目。


Here is what official docs said

updateIn(keyPath: Array<any>, updater: (value: any) => any): List<T>
updateIn(keyPath: Array<any>, notSetValue: any, updater: (value: any) => any): List<T>
updateIn(keyPath: Iterable<any, any>, updater: (value: any) => any): List<T>
updateIn(keyPath: Iterable<any, any>, notSetValue: any, updater: (value: any) => any): List<T>

There is no way normal web developer (not functional programmer) would understand that!

I have pretty simple (for non-functional approach) case.

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.List.of(arr);

How can I update list where element with name third have its count set to 4?

解决方案

The most appropriate case is to use both findIndex and update methods.

list = list.update(
  list.findIndex(function(item) { 
    return item.get("name") === "third"; 
  }), function(item) {
    return item.set("count", 4);
  }
); 

P.S. It's not always possible to use Maps. E.g. if names are not unique and I want to update all items with the same names.

这篇关于如何使用ImmutableJS更新List内的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆