mlin956
mlin956

Reputation: 365

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!

Upvotes: 4

Views: 5164

Answers (3)

Bhullnatik
Bhullnatik

Reputation: 1312

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

Upvotes: 6

hazardous
hazardous

Reputation: 10837

A much cleaner version, based on forEach. Its a sideeffect (mutates an otherwise immutable list), so the syntax is similar to using a mutable list -

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

And yes, there's a version for Map too.

Upvotes: 0

superui
superui

Reputation: 672

It is easy.

list = Immutable.List.of(1, 2, 3, 4);
list = list.set(list.indexOf(2), 5);

console.log(list.get(1));  //5

Upvotes: 6

Related Questions