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

sfletche picture sfletche · Jan 13, 2017 · Viewed 10.9k times · Source

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?

Answer

sfletche picture sfletche · Aug 15, 2017

One solution would be to leverage the object spread operator

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