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?
One solution would be to leverage the object spread operator
const newObject = ['a', 'b', 'c'].reduce((result, item, index) => ({
...result,
[item]: index,
}), {});