How to loop through Immutable List like forEach?

放肆的年华 提交于 2019-12-10 12:31:45

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/37692999/how-to-loop-through-immutable-list-like-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!