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

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

问题描述

这是官方文档所说的

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>

普通的 Web 开发人员(不是函数式程序员)无法理解这一点!

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);

如何更新 list,其中名称为 third 的元素的 count 设置为 4?

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

推荐答案

最合适的情况是同时使用 findIndexupdate 方法.

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天全站免登陆