Search code examples
javascripteslinteslint-config-airbnb

Array forEach() vs reduce()


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)


Solution

  • 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, {});