在immutable.js中更改列表中的一项
Changing one item in a list In immutable.js
我使用的是immutable.js,我的数据结构如下:
class ItemList extends Record({
items: new List()
})
我想写一个函数,改变这个列表中的一个项目,并保持其他项目不变。例如,一个{1,2,3,4}的列表,我需要一个函数,如果一个项等于2,请将其更改为5。
我正在使用类似的东西
updateInfo(updatedInfo) {
return this.withMutations(itemList => {
itemList.set('items', list);
});
}
我的问题是在这个功能中,我如何才能只更新一个项目?我应该把if判断放在哪里?
谢谢!
NB:正如另一个答案所提到的,还有一种未记录的indexOf
方法,在某些情况下可能更容易使用,只将要查找的值作为参数。
使用findIndex
查找需要更改的值的索引,使用set
查找要更改的索引:
list = Immutable.List.of(1, 2, 3, 4);
list = list.set(list.findIndex(function(item) {
return item === 2;
}), 5);
ES6:
list = list.set(list.findIndex((item) => item === 2), 5);
如果你需要旧值来更改它,你可以使用update
而不是像那样设置
list = list.update(list.findIndex(function(item) {
return item === 2;
}), function(oldValue) {
return 5;
});
ES6:
list = list.update(list.findIndex((item) => item === 2), (oldValue) => 5);
这很容易。
list = Immutable.List.of(1, 2, 3, 4);
list = list.set(list.indexOf(2), 5);
console.log(list.get(1)); //5
一个更干净的版本,基于forEach。这是一个副作用(变异一个不可变的列表),因此语法类似于使用可变列表-
var list = Immutable.List.of(1, 2, 3, 4);
// Notice no LHS assignment is required as
// forEach is a side-effect method.
list.forEach((value, index, theList) => {
// You can check either value, or index
if (index === soAndSo
|| value.something === something){
// Just change the value!
value.prop = someNewValue;
// Or, in the above case where value
// is not a reference
theList.set(index) = newValue;
// As we found and changed the value
// of interest, lets exit forEach
return false;
}
});
是的,Map也有一个版本。
相关文章:
- 如何从对象数组中获取最后一项
- 为什么只有最后一项显示,而不是全部显示
- 删除最后一项jquery
- $q.all当输入数组中的一项不是promise时,Typescript检查器失败
- 为什么我的“for”循环只获取 html 中的最后一项
- 我无法将下拉列表的默认值设置为最后一项
- 流星批量插入仅插入最后一项
- 我怎么能知道元素是最后一项
- 如何删除WinJS组绑定列表的最后一项
- 在immutable.js中更改列表中的一项
- 使用handlers.js模板以数组中的最后一项为条件
- AngularJs ng显示当列表中的某一项在一行中为true时
- node.js:将一个异步函数列表应用于列表列表中的每一项
- 将innerHTML从列表中的一项复制到元素的内容中
- 如何使用Angular.js获得多选择数据,并在列表的每一项中添加复选框
- 不能让.offset()方法在迭代一组列表项时工作
- 删除列表中的最后一项
- 用生成器异步调用列表的每一项
- 将属性移动到列表中的上一项
- 样式提要条目列表中的最后一项(googlefeedApi)