Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update element inside List with ImmutableJS?

Here is what official docs said

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> 

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

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

like image 561
Vitalii Korsakov Avatar asked Apr 12 '15 13:04

Vitalii Korsakov


People also ask

Are lists immutable in JavaScript?

Lists are immutable and fully persistent with O(log32 N) gets and sets, and O(1) push and pop. Lists implement Deque, with efficient addition and removal from both the end ( push , pop ) and beginning ( unshift , shift ).

Is JavaScript set immutable?

JavaScript primitives (undefined, null, boolean, number, string, and symbol values) are immutable by default, so you are already prevented from permanently altering primitive values themselves.

Is map immutable in JavaScript?

Map's keys can be of any type, and use Immutable.is to determine key equality. This allows the use of any value (including NaN) as a key. Because Immutable.is returns equality based on value semantics, and Immutable collections are treated as values, any Immutable collection may be used as a key.


1 Answers

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.

like image 162
Vitalii Korsakov Avatar answered Sep 28 '22 15:09

Vitalii Korsakov