Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing one item in a list In immutable.js

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!

like image 869
mlin956 Avatar asked Dec 19 '22 18:12

mlin956


1 Answers

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);
like image 106
Bhullnatik Avatar answered Jan 02 '23 21:01

Bhullnatik