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.
How can I change my code to avoid the parsing error while keeping the code short?
Shall I disable the ESLint check for this error?
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;
}, {});
...
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})), {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With