JavaScript 上的 ESLint 错误(意外标记 ...)减少到字典

ESLint error (Unexpected token ...) on JavaScript reduce to dictionary

我确实有一个 JavaScript 代码片段,它遍历一组字段以查找特定属性并将它们添加到字典中。另外,请参阅 this site 以获取另一个示例。

return this.getFields()
    .reduce((mappings, field) => ({...mappings, [field.id]: field.name}), {});

这很好用。但是我收到三个点的 Eslint 代码样式解析错误。

Unexpected token ...

关于这个的三个问题。

  1. 如何更改我的代码以避免解析错误,同时保持代码简短?

  2. 我应该禁用 ESLint 检查这个错误吗?

  3. ... 符号的名称是什么?

我的解决方法如下。但我更愿意保留原始版本。

  return this.getFields()
    .reduce(function(mappings, field) {
      mappings[field.id] = field.name;
    }, {});

... 符号用于 Spread syntax 其中 returns 新数组或对象的副本。例如

 var arr1 =[1, 2, 3],

如果您想创建一个包含第 4 项的新数组,您可以这样做:

var arr2 = [...arr1, 4] //[1, 2, 3, 4]

或者,如果您这样做:

var obj = {a: 1, b: 2},
var obj2 = {...obj, b:3} //you create a copy of obj and then modify a property. So obj2 = {a:1, b:3}

您原来的 obj 的 属性 b 不受影响。

The --fix option on the command line can automatically fix some of the problems reported by this rule.

您可以将此添加到 ES Lint 的配置中以了解传播运算符:

 {
    "parserOptions": {
        "ecmaVersion": 2018
    }
}

参考:https://eslint.org/docs/rules/rest-spread-spacing

由于您正在使用 reduce 并避免突变,因此以下内容同样有效:

 return this.getFields()
    .reduce(function(mappings, field) {
      mappings[field.id] = field.name;
      return mappings // <--- I think you may want to return this
    }, {});

如果您愿意,您也可以考虑使用 Object.assign 代替传播运算符 ...

return this.getFields()
    .reduce((mappings, field) => (Object.assign(mappings, {[field.id]: field.name})), {});