Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }, {});
like image 509
Matthias Avatar asked Jun 24 '20 15:06

Matthias


1 Answers

... 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})), {});
like image 74
ABGR Avatar answered Oct 09 '22 20:10

ABGR