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

1

5

I do have a JavaScript code snippet that iterates through an array of fields looking for specific properties and adding those to a dictionary. Also, see this site for another example.

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

This works perfectly fine. But I'm getting an Eslint code style parsing error for the three dots.

Unexpected token ...

Three questions about this.

  1. How can I change my code to avoid the parsing error while keeping the code short?

  2. Shall I disable the ESLint check for this error?

  3. What is the name for the ... notation?

My workaround would be the following. But I would prefer keeping the original version.

  return this.getFields()
    .reduce(function(mappings, field) {
      mappings[field.id] = field.name;
    }, {});
Northrup answered 24/6, 2020 at 15:14 Comment(1)
... notation is for spread operator to return a copy of new array or objectsAxial
A
6

... notation is for Spread syntax which returns a copy of new array or objects. For e.g

 var arr1 =[1, 2, 3],

If you want to create a new array with an item 4, you can do so:

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

Or, If you do like this:

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}

Your original obj's property b remains unaffected.

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

You can add this in your configurations for ES Lint to understand the spread operator:

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

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

The following would work just as well since you're using reduce and avoiding mutation:

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

You may also consider using Object.assign in place of spread operators ... if you like.

return this.getFields()
    .reduce((mappings, field) => (Object.assign(mappings, {[field.id]: field.name})), {});
Axial answered 24/6, 2020 at 15:28 Comment(3)
Your last example is missing the braces of the object.Morale
@Morale Thanks :) Corrected.Axial
I decided to change the arrow functions to the default function closures (as you listed at the very bottom). Actually good choice sind the spread syntax creates copies which is not needed for an accumulator in a reduce function.Northrup

© 2022 - 2024 — McMap. All rights reserved.