I'm using immutable.js, my data structure is like:
class ItemList extends Record({
items: new List()
})
I want to write function that change one item in this list and keep other the same. For example, a list of {1, 2, 3, 4}, I need a function if an item equals 2, change it to 5.
I'm using something like
updateInfo(updatedInfo) {
return this.withMutations(itemList => {
itemList.set('items', list);
});
}
My question is in this function, how can I just update one item? where should I put the if judgment?
Thanks!
NB: As mentioned by another answer, there is also the undocumented indexOf
method which may be easier to use in some cases, taking only the value to find as parameter.
Using findIndex
to find the index of the value you need to change and set
with the index to change:
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);
If you need the old value to change it, you can use update
instead of set like:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With