问题
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