sfletche sfletche -3 years ago 204
Javascript Question

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

I've recently added the eslint rule

.

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download