alim1990
alim1990

Reputation: 4972

How to map an array key indexes into other key names from drop down list form controls?

I need to change the array key names into others specified by users, using drop down lists as reactive form controls.

Lets say I have the following array:

dataArray = [
    { id: 7854496, name: 'Peterson', gender: 'Male' },
    { id: 7054457, name: 'Peterson', gender: 'Female' },
    { id: 6954481, name: 'Peterson', gender: 'Female' },
];

The user will, will select the drop down list related to id, and change into another, lets say index, and so on for the others. Therefore, when the user click on the button with the mapData() method, the array should look like:

dataArray = [
    { index: 7854496, familyName: 'Peterson', sex: 'Male' },
    { index: 7054457, familyName: 'Peterson', sex: 'Female' },
    { index: 6954481, familyName: 'Peterson', sex: 'Female' },
];

Here is the mapData() method:

mapData() {
  this.odkDataIndexes.forEach((arrayIndexControl) => {
    let newIndex = this.indexesForm.get(arrayIndexControl).value;
    this.dataArray = this.dataArray.map((item) => {
      console.log(item);
      return {
        newIndex: item[arrayIndexControl]
      };
    });
  });
}

I am doing it this way, because, I am mapping some field to others, so I can do a migration from database into another, where the array should have a specific array key names.

Here is a stackblitz having the full code.

Upvotes: 0

Views: 51

Answers (1)

ashutosh
ashutosh

Reputation: 334

you can do something like this

mapData() {    
    var newDataArray = [];
    this.dataArray.forEach(e=>{
      var newItem = {};
      this.odkDataIndexes.forEach((arrayIndexControl) =>{
        // console.log(e[arrayIndexControl]);
        newItem[this.indexesForm.get(arrayIndexControl).value] = e[arrayIndexControl];
      });
      newDataArray.push(newItem);
    });
    this.dataArray = newDataArray;
}

Upvotes: 1

Related Questions