Array forEach() vs reduce() [closed]

北城余情 提交于 2019-12-12 03:27:35

问题


what do you think is the best way to do ?

Reduce Way :

const result = Object.keys(params).reduce(
      (previous, key) => {
        if (this.model.hasOwnProperty(key)) previous[key] = this.model[key](params[key]);
        return previous;
  }, {});

ForEach Way:

const result = {};
Object.keys(params).forEach(key => {
      if (this.model.hasOwnProperty(key)) result[key] = this.model[key](params[key]);
    });

I'm using airbnb eslint and it doesn't like the reduce way since I modify previous (no-param-reassign)


回答1:


I think the reduce is a lot nicer because it doesn't spill vars all over the place. You could make it a little better yet, imo.

var result = Object.keys(params).reduce((res,k)=>
  this.model.hasOwnProperty(k)
    ? Object.assign(res, {[k]: this.model[k](params[k])})
    : res, {});


来源:https://stackoverflow.com/questions/37461580/array-foreach-vs-reduce

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