How to handle eslint no-param-reassign rule in Array.prototype.reduce() functions

扶醉桌前 提交于 2020-11-30 06:13:34

问题


I've recently added the eslint rule no-param-reassign.

However, when I use reduce to build out an object (empty object as initialValue), I find myself needing to modify the accumulator (first arg of callback function) on each callback iteration, which causes a no-param-reassign linter complaint (as one would expect it would).

const newObject = ['a', 'b', 'c'].reduce((result, item, index) => {
  result[item] = index; // <-- causes the no-param-reassign complaint
  return result;
}, {});

Is there a better way to build out an object with reduce that doesn't modify the accumulator argument?

Or should I simply disable the linting rule for that line in my reduce callback functions?


回答1:


I just wrap the reduce functions in a lint rule disable block, ie:

/* eslint-disable no-param-reassign */
const newObject = ['a', 'b', 'c'].reduce((result, item, index) => {
  result[item] = index;
  return result;
}, {});
/* eslint-enable no-param-reassign */



回答2:


One solution would be to leverage the object spread operator

const newObject = ['a', 'b', 'c'].reduce((result, item, index) => ({
  ...result,
  [item]: index, 
}), {});



回答3:


Well, you could do (result, item) => Object.assign({}, result, {[item]: whatever}) to create a new object on every iteration :-)

If you want to trick the linter, you could use => Object.assign(result, {[item]: whatever}) (which does the same as your current code but without an explicit assignment), but yeah I guess you should simply disable that rule.



来源:https://stackoverflow.com/questions/41625399/how-to-handle-eslint-no-param-reassign-rule-in-array-prototype-reduce-function

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