How can I add a new property with dfiferent values to an array of object, in TypeScript?

Viewed 64

example:

equipment: object[] = [
       {name: 'Duct Tape', mass: 0.5},
       {name: 'Space Camera', mass: 20},
       {name: 'Food', mass: 150},
       {name: 'Oxygen Tanks', mass: 400},
             ];

I want the object to be

equipmentItems: object[] = [
       {name: 'Duct Tape', mass: 0.5 , age = 25},
       {name: 'Space Camera', mass: 20 , age = 30},
       {name: 'Food', mass: 150 , age = 35},
       {name: 'Oxygen Tanks', mass: 400 , age = 40}
      ]

I know that I could loop over to add property like

for(let i=0;i<equipments.length;i++){
  let equipments[i].age=25;
}

but this will add 25 as age to all the equipments.Is there a quick way to do this?

2 Answers

Use a counter to hold age values and increment it in each iteration, along with the spread operator:

let counter = 20;
this.equipment = this.equipment.map(e => {
  return {
    ...e,
    age: counter += 5,
  };
});

Also, since we are using typescript create an interface to represent equipment i.e

export interface Items {
  name: string;
  mass: number;
  age?: number;      // optional since it is added later
}

now define the array by using:

equipment: Items[] = [
  { name: 'Duct Tape', mass: 0.5 },
  { name: 'Space Camera', mass: 20 },
  { name: 'Food', mass: 150 },
  { name: 'Oxygen Tanks', mass: 400 },
];

I am updating my answer considering the age as a random number generated between 20 and 60. You can change the min and max values as per your requirement

equipment=[];
equipmentItems=[];

ngOnInit(){
  this.equipment= [
       {name: 'Duct Tape', mass: 0.5},
       {name: 'Space Camera', mass: 20},
       {name: 'Food', mass: 150},
       {name: 'Oxygen Tanks', mass: 400},
        ]; 

        this.equipmentItems=this.equipment;

        this.equipmentItems.forEach((arrayItem, index)=> {
        this.equipmentItems[index].age=this.generateRandomAge(20, 60);
       });
}

 generateRandomAge(min, max) {
  return Math.floor(min + Math.random()*(max + 1 - min))
}

Working code: https://stackblitz.com/edit/angular-ivy-rjmdn1?file=src/app/app.component.html

To generate random numbers without constraint:

this.equipmentItems.forEach((arrayItem, index)=> {
        this.equipmentItems[index].age=this.generateRandomAge(-20, 20);
       });
Related