Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to modify a key in an array of objects by its index?

I am working on React. I’ve created a Class to create a training program.
In function of the training frequency number n selected by the user I need to create 1,2..n training programs.
This is the class I created:

class Training {
  km = 0;
  programNum = 1;
  success = false;
  constructor(frequency, years) {
    this.frequency = frequency;
    this.years = years;
  }
}

This is the function for the training program:

const createTraining = (frequency, years) => {
    const newTraining = new Training(frequency, years);
    var temp = [];
    for (var i = 0; i < frequency; i++) {
      temp.push(newTraining);
    }}

 temp.forEach((item, i) => {
      item.programNum = i + 1;
    });
  console.log(temp);


// For frequency=4, it creates an array of 4 trainings:
(4) [Training, Training, Training, Training]
0: Training {km: 0, programNum: 4, success: false, frequency: '4', years: '2'}
1: Training {km: 0, programNum: 4, success: false, frequency: '4', years: '2'}
2: Training {km: 0, programNum: 4, success: false, frequency: '4', years: '2'}
3: Training {km: 0, programNum: 4, success: false, frequency: '4', years: '2'}
length: 4

Inside this array I would like to assign 1,2,3,4 so I user forEach but instead it assigns 4,4,4,4 to the key programNum
I would like it to be like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(4) [Training, Training, Training, Training]
0: Training {km: 0, programNum: 1, success: false, frequency: '4', years: '2'}
1: Training {km: 0, programNum: 2, success: false, frequency: '4', years: '2'}
2: Training {km: 0, programNum: 3, success: false, frequency: '4', years: '2'}
3: Training {km: 0, programNum: 4, success: false, frequency: '4', years: '2'}
length: 4

I can’t figure out how to do that.

>Solution :

The problem is that your pushing a reference to the same object 4 times.
Do this instead:

const createTraining = (frequency, years) => {

    for (var i = 0; i < frequency; i++) {
        const newTraining = new Training(frequency, years);
        newTraining.programNum = i + 1;
        temp.push(newTraining);

    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading