Home > Software engineering >  How to modify a key in an array of objects by its index?
How to modify a key in an array of objects by its index?

Time:01-06

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:

(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.

CodePudding user response:

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);

    }
}

CodePudding user response:

A small modification to the executable statement should give you the desired functionality.

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

// slightly modified code
const createTraining = (frequency, years) => {
  let temp = [];

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

  return temp;
};

// test result
const result = createTraining(4, 2);
console.log(result);
  • Related