Issue with ESLint: Unexpected token found in JavaScript when converting to a dictionary

I've implemented a JavaScript code snippet that loops through an array of fields to find specific properties and then adds them to a dictionary. For another example, you can check out this site.

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

The functionality works perfectly fine; however, I am encountering an Eslint code style parsing error related to the three dots.

Unexpected token ...

This situation raises three questions:

  1. Is there a way I can modify my code to prevent the parsing error without adding unnecessary length?

  2. Should I consider disabling the ESLint check for this particular error?

  3. What is the technical term for the ... notation in JavaScript?

As a temporary solution, I could use the following alternative approach. Nonetheless, I would prefer sticking with the original version.

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

Answer №1

The ... notation represents the Spread syntax, which creates a duplicate of new arrays or objects. For example:

 var arr1 = [1, 2, 3],

To add an element 4 to a new array:

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

Similarly, for objects:

var obj = {a: 1, b: 2},
var obj2 = {...obj, b:3} //creates a copy of obj and modifies a property. So obj2 = {a:1, b:3}

The original property b in your obj remains unchanged.

The --fix option in the command line can automatically correct some reported issues by this rule.

You can include this configuration in ES Lint for recognizing the spread operator:

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

For better functionality without mutating data, consider using reduce:

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

Alternatively, you can use Object.assign instead of spread operators ...:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing for the presence of a child element within a parent component in React

Below is the structure of my component: const Parent = (props) => { return <div>{props.children}</div>; }; const Child1 = (props) => { return <h2>child 1</h2>; }; const Child2 = (props) => { return <h2>child 2 ...

Halt the iteration once you reach the initial item in the array

I am encountering a challenge with this for loop. My goal is to extract the most recent order of "customers" and save it in my database. However, running this loop fetches both the failed order and the recent order. for (var i = 0; i < json.length; ...

What is the best approach for incorporating sub-navigation within a page popup in a Next.js project?

In the midst of my Next.js project, there is a requirement to showcase a chat popup consisting of multiple sub-pages like user registration, conversation page, and more. Hence, seamless navigation inside this popup is necessary. The idea is not to alter th ...

Answer found: How to effectively filter data arrays in a React client application

I've been working on mapping the GraphQL data onto a React app and I'm facing an issue with making the filtration dynamic for user input. Currently, I am using .filter() to apply client-side filtration but struggling to figure out how to make it ...

Angular successfully compiled without any issues despite the explicit cast of a number into a string variable

As I delve into the initial concepts of Angular, I have come across a puzzling situation. Here is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'sandbox', template: ` <h1>Hello {{ nam ...

Retrieve information from jsonObject

Can anyone help me with counting the number of passes and fails for each subject in a JSON object array? Here is an example: [{"Subject":"Maths","status:"Pass"},{"Subject":"Maths","status:"Pass"}, {"Subject":"Maths","status:"Fail"},{"Subject":"Maths ...

Adding QML code into a Jade file

Currently working on developing a straightforward video streaming application using Node.js and integrating the WebChimera plugin. The player configuration is done in QML with Chimera, and I am facing numerous errors during the compilation process in Jade. ...

Sending a piece of state information to a different component

Hey, I'm a new React developer and I'm struggling with a particular issue. I've included only the relevant code snippets from my app. Basically, I want to retrieve the data from the clicked Datagrid row, send it to a Dialog form, and then p ...

Video player on website experiencing issues with playing VAST ads

Hey there! Check out this awesome site for Music Videos: (Music Videos(Player)) I've been testing different options, but if you have a better suggestion, please let me know. Any help would be really appreciated. If I can't figure it out on my o ...

I am receiving a Promise object with a status of "pending" within an asynchronous function on node.js

I have a nodejs class function that retrieves all rows from the database. module.exports = class fooClass { static async fooFunc() { const mysql = require('mysql'); const util = require('util'); const conn = mysql.createC ...

What is the best way to transfer information between different pages in an HTML document?

I am facing a specific requirement where I must transfer form data from one HTML page to another HTML page. The process involves a total of 5 pages, with the user entering data in the following order: 1st page: Name 2nd page: Weight 3rd page: Height 4t ...

Even after setting [attr.disabled]="false" in Angular, the Textarea still remains disabled

I am currently utilizing ngModel for a textarea, and I would like to be able to enable and disable the textarea based on a certain condition. Even though I have bound it correctly and the value is changing to [attr.disabled]="false", the textarea remains d ...

MongoDB does not treat aggregate match pipeline as equal to in comparisons

I've been tackling an aggregate pipeline task for MongoDB where I need to retrieve items that do not have a specific user ID. Despite my efforts, I'm struggling to get it right. I attempted using $not, $ne, and $nin in various ways but couldn&ap ...

Using React client to accept messages from a Socket.io server: A guide

I have a setup where a Node.js server with Socket.io is used to send messages between React clients. Currently, I can send a message from Client 1 to Client 2, but the recipient must click a button to view the message on their screen. I am trying to make i ...

Rails offers a unique hybrid approach that falls between Ember and traditional JavaScript responses

My current project is a standard rails application that has primarily utilized HTML without any AJAX. However, I am planning to gradually incorporate "remote" links and support for JS responses to improve the user experience. While I acknowledge that gener ...

Establishing a recurring interval when the component mounts for a specified period of time

I have read through several Q&As on this topic, but I am still unable to pinpoint what mistake I am making. The code snippet below is meant to display a countdown in the console and update the DOM accordingly, however, it only prints 0s in the console ...

Passing events between sibling components in Angular 2Incorporating event emission in

Having some trouble emitting an event from one component to another sibling component. I've attempted using @Output, but it seems to only emit the event to the parent component. Any suggestions? ...

The contents of a Javascript array are not appearing within a div element

I have developed a program that reads JSON data related to a concert event. The JSON file consists of an object named global, which includes details about the band name and venue. Additionally, there is a tickets object that contains information on all ava ...

Utilize dynamically generated form fields to upload multiple files at once

Currently, as I delve into learning the MEAN stack, I am encountering difficulties with file uploads. Specifically, within a company form: this.companyForm = this.fb.group({ trucks: this.fb.array([]), ... }); The 'trucks' field i ...

Is there a way to confirm whether or not two files are identical?

Is there a reliable method to determine if two files are identical? I've been using a solution that involves downloading the first part of each file, converting the data to base64, and then comparing them. However, I've encountered an issue wher ...