Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Class - map array of variables

Let's say that I have a list of 5 people's name

let listNames = [Sam, Ash, Moe, Billy, Kenzi]

and I want for each of the names to have properties of doneHomeWork and lazy using class

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

instead of assigning each names as so :

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

I was thinking doing this

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

However, in my ESLint it's giving me an error

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

This seems trivial, but for some reason I am having trouble re-factoring this.

like image 571
Alejandro Avatar asked May 21 '26 18:05

Alejandro


1 Answers

The issue is that the name variable is the one used for cycling inside the loop. You're changing this value in the first iteration of the loop. This is the reason of your error Assignment to function parameter 'name' no-param-reassign.

Then you are trying to use dynamic names as variables names. If you want to do it, the way is using bracket notation, so you could do it in this way:

class Person {
    constructor() {
        this.doneHomeWork = 0
        this.lazy = false
    }
}
let persons = [];
let listNames = ['Sam', 'Ash', 'Moe', 'Billy', 'Kenzi'];

correctListNames.forEach(name => {
    persons[name] = new Person()
})

console.log(persons);
like image 132
quirimmo Avatar answered May 24 '26 06:05

quirimmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!