Using ES6 Classes to map an array of variables

If I have a list of 5 people's names, such as Sam, Ash, Moe, Billy, Kenzi, and want each name to have properties like doneHomework and lazy using a class:

class Person {
    constructor() {
        this.doneHomeWork = 0;
        this.lazy = false;
    }
}

Instead of manually assigning each name like this:

const Sam = new Person();
const Ash = new Person();
const Moe = new Person();
const Billy = new Person();
const Kenzi = new Person();

I thought about doing this:

listNames.forEach(name => {
    name = new Person();
})

But my ESLint is showing an error:

Assignment to function parameter 'name' - no-param-reassign

This may seem trivial, but I'm having difficulty refactoring this code.

Answer №1

The problem arises from the usage of the name variable within the loop cycle. The error occurs because you are updating this variable in the initial iteration of the loop, triggering the

Assignment to function parameter 'name' no-param-reassign
error message.

Furthermore, attempting to assign dynamic names as variable identifiers is problematic. To achieve this, consider utilizing bracket notation. Here's how you can implement it:

class Student {
    constructor() {
        this.homeworkCompleted = 0
        this.attendance = true
    }
}
let students = [];
let studentNames = ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'];

studentNames.forEach(name => {
    students[name] = new Student()
})

console.log(students);

Answer №2

In order to achieve this functionality, you can utilize ES6 array destructuring by creating a new instance of the Person class for each name.

class Person {
  constructor() {
    this.completedTasks = 0;
    this.isLazy = false;
  }
}

const [John, Alice, Mike, Sarah, Emma] = Array.from(Array(5), e => new Person)

console.log(John)
console.log(Alice)

Answer №3

Instead of attempting to dynamically generate this

const Alex = new Person();
const Emily = new Person():

You can achieve a similar result like so,

const people = {
  Alex: new Person(),
  Emily: new Person(),
};

Then you can access them using people['Alex'] or people.Alex. To accomplish this from an array,

const names = ['Alex', 'Emily'];
const people = {};
names.forEach(name => {
  people[name] = new Person();
});

Regarding the eslint warning that you are receiving, it is due to your attempt to modify a function parameter. You can disable it by setting the rule to 0 in your eslint configuration file. However, I would advise against doing so.

Answer №4

To accomplish this task, you can make use of the ES6 destructuring feature as demonstrated below:

class Student {
    constructor() {
        this.completedAssignments = 0;
        this.attendance = true;
    }
}
let students = [];
for(let i=0; i<5; i++) {
    students.push(new Student());
}

const [Alice, Bob, Charlie, Dave, Eve] = [...students];

console.log(Alice);

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

Having difficulty retrieving the Area and Range information in ChartJS

I am new to working with HTML5 and ChartJS. I have noticed two different types of declarations when attaching JS Chart Versions 1.0.1 and 2.1.1. Can you please provide some insight into this? Additionally, I am facing an issue where the stripes behind the ...

develop a Java 2D array

Currently, I have a Java code set up to calculate the average of an array and it's working flawlessly. However, I am looking to make modifications so that it can handle a 2D array (Two-dimensional). import java.util.*; public class Test3{ public st ...

Watching for changes to an object's value in an AngularJS service triggered by a controller from a separate module (Extended Edition)

Referring to this discussion on Stack Overflow: AngularJS trigger and watch object value change in service from controller The original question was about watching for changes in a service from a controller. I am interested in extending this concept to ...

Use jQuery to update the field without affecting the observable

Greetings to the wonderful stackoverflow community! I recently delved into using knockout just a few days back. Currently, I am utilizing it to create a dynamic menu builder for a CMS project that I'm deeply engrossed in. If you'd like to take ...

How can I transfer a selected value from a unique dropdown component to react-hook-form?

I am utilizing react-hook-form for form validation in this Gatsby project. However, my dropdown component is not a <select> tag but a customized component created with divs and an unordered list. This design choice was made to meet our specific custo ...

Optimizing Nginx for caching server-side rendered (SSR) web pages developed using React and Next.js

After creating an application where some pages are rendered on the server side, I noticed that something wasn't right. When viewing the requested pages in my browser, everything seemed normal. However, when I sent a CURL request to the page and saved ...

"Executing the ajax send() function does not result in any changes to the

Just starting to explore ajax and I need some help. Can anyone explain why the address bar is not updating when using ajax send()? The connection is working, but it keeps displaying "There is no variable!" PS: Please note that I prefer not to use JQuery. ...

Is there a method available to streamline the process of generating .json files for language translations?

Working with translation files can be a tedious task, especially when adding new keys for different languages. Making sure that each key is included in all the JSON files can lead to errors and repetitive editing. Is there a more efficient way to handle t ...

The .slice() function in TypeScript has the ability to alter the initial array

I am diving into TypeScript and just tackled my first slice() method. My understanding is that the slice() method is supposed to create a copy of an array. Here's a snippet of the code: class ChapterOne { // Gauss Jordan Elimination // No ...

Scraping with Node.js and PhantomJS for dynamic content

After successfully installing both PhantomJs and its npm interface phantom, I have set the code to load my desired page with the updated syntax. However, for some reason, the dynamically generated elements in the right sidebar are not being picked up by ph ...

Middleware functions in Mongoose for pre and post actions are not being triggered when attempting to save

After carefully reviewing the documentation, I am still unable to pinpoint the issue. The pre & post middleware functions do not appear to be functioning as expected. I have made sure to update both my node version and all modules. // schema.js const sch ...

Vue: restrict entry to the view unless props are configured

Currently, I am in the process of creating a Vue game that consists of two main views: a 'setup' view and a 'play' view. The values that are configured in the setup view are then passed as props to the play view, initiating the game wit ...

Searching by element within a JSON array

I've tried various solutions from different sources but haven't been able to find the correct answer yet. create table mstore ( muuid uuid PRIMARY KEY, msid text, m_json JSONb[] not NULL ); Inserted the first row: insert into mstore (muuid, msid ...

Similar to Angular ui-router 1.0.3, what is the equivalent function for reloadOn

After updating to UI-router v1.0.3 from v0.3.2, I noticed that the reloadOnSearch feature has been removed from the stateConfig. I'm having trouble finding the equivalent of reloadOnSearch in v1.0.3. It doesn't seem to be documented anywhere. A ...

What is the necessity for an additional item?

After exploring the Angular Bootstrap UI and focusing on the $modal service, I came across an intriguing discovery. In their demo at 'http://plnkr.co/edit/E5xYKPQwYtsLJUa6FxWt?p=preview', the controller attached to the popup window contains an i ...

What's the best way to link two http requests in AngularJS?

Currently, I am facing the challenge of chaining two http calls together. The first call retrieves a set of records, and then I need to fetch finance data for each individual record. flightRecordService.query().$promise.then(function (flightRecords) { $ ...

"There is an issue with the payload size: request entity is too large. What is the solution for handling this in Nest

I am facing an issue where I need to send a request containing a large base64 string, approximately around 2 MB. However, the server keeps throwing an error message. How can I prevent this error from occurring: [Nest] 1666 - 11/01/2021, 1:50:58 PM ERRO ...

Using Jquery for Animation: Tips on Revealing Text After Changing Element Color or Styles

Hey everyone, I ran into a bit of trouble while working with jQuery and trying out some animations. My goal was to make a textbox appear and display text when a button is highlighted, similar to a gallery setup. However, I managed to get halfway through th ...

observing which specific element corresponds to the nth child?

Exploring the concept illustrated in https://api.jquery.com/eq/, imagine a scenario with the following HTML structure: <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item ...

Loading a stack of images in MATLAB: a simple guide

There are a total of 170 PNG images stored in a specific folder. My goal is to efficiently load and organize them into a matrix, array, or cell array for easy accessibility and modification. However, I'm currently facing difficulties right from the st ...