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

前端 未结 3 1625
深忆病人
深忆病人 2021-02-03 18:14

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 need

相关标签:
3条回答
  • 2021-02-03 18:36

    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 */
    
    0 讨论(0)
  • 2021-02-03 18:49

    One solution would be to leverage the object spread operator

    const newObject = ['a', 'b', 'c'].reduce((result, item, index) => ({
      ...result,
      [item]: index, 
    }), {});
    
    0 讨论(0)
  • 2021-02-03 18:59

    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.

    0 讨论(0)
提交回复
热议问题