0

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)

TylerH
  • 20,799
  • 66
  • 75
  • 101
Titozzz
  • 189
  • 2
  • 6
  • 16

1 Answers1

2

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, {});
Mulan
  • 129,518
  • 31
  • 228
  • 259