18

I would like to loop through Immutable List, I used List.map to do it, it can be worked, but not good. is there are a better way? Because I just check each element in array, if the element match my rule, I do something, just like Array.forEach, I don't want to return anything like Array.map.

for example, it is my work now:

let currentTheme = '';
let selectLayout = 'Layout1';
let layouts = List([{
  name: 'Layout1',
  currentTheme: 'theme1'
},{
  name: 'Layout2',
  currentTheme: 'theme2'
}])


layouts.map((layout) => {
  if(layout.get('name') === selectLayout){
     currentTheme = layout.get('currentTheme');
  }
});
hazardous
  • 10,627
  • 2
  • 40
  • 52
Seven Lee
  • 597
  • 4
  • 9
  • 21

1 Answers1

16

The method List.forEach exists for Immutable.js lists.

However, a more functional approach would be using the method List.find as follows:

let selectLayoutName = 'Layout1';
let layouts = List([Map({
  name: 'Layout1',
  currentTheme: 'theme1'
}),Map({
  name: 'Layout2',
  currentTheme: 'theme2'
})])


selectLayout = layouts.find(layout => layout.get('name') === selectLayoutName);
currentTheme = selectLayout.get('currentTheme')

Then your code doesn't have side-effects.

Mateus Zitelli
  • 1,222
  • 1
  • 13
  • 23
  • Thanks! List find is like `Array.filter`, that what I need :) – Seven Lee Jun 08 '16 at 06:04
  • 2
    The difference is that ```List.find``` returns the first match, while ```Array.filter``` provide a list of all elements that satisfies the condition. – Mateus Zitelli Jun 08 '16 at 22:06
  • 1
    @SevenLee `List.find` is pretty much like `Array.find` and `List.filter` is like `Array.filter`. It is important to remember it. – Mihail Nov 14 '17 at 13:03