Home > other >  How to add and element with a value into an array of objects by using for loop
How to add and element with a value into an array of objects by using for loop

Time:10-12

I have an array of objects and I want to add and new id element with increasing value into each object. In the end, I except like this

bicycle = [
{
    categorie: 'Road Bike',
    img: '',
    title: '',
    price: '',
    description: '',
    id: 0
},
{
    categorie: 'Road Bike',
    img: '',
    title: '',
    price: '',
    description: '',
    id: 1
}
]

For this result, when I try to do it with a for loop. I will get always same id value (not increasing).

var bikeObject:any = {
    categorie: 'Road Bike',
    img: '',
    title: '',
    price: '',
    description: ''
}

var bicycle:any = [];

function func(){
  for(let i=0; i < 100; i  ){
    bicycle.push(bikeObject);
  }
  for(let i=0; i < 100; i  ){
    bicycle[i].id = i;
  }
  console.log(bicycle);
}

func();

What should I do to get increasing id values instead of the same. I tried also .map and forEach functions, but all of them gave the same result.

CodePudding user response:

bikeObject is only declared once. This means you're pushing the same object into the array 100 times. You need to move the declaration of bikeObject inside the first for-loop. You could also merge the for-loops like so:

var bicycle: any[] = [];

function func(){
  for(let i=0; i < 100; i  ){
    var bikeObject = {
      id: i,
      categorie: 'Road Bike',
      img: '',
      title: '',
      price: '',
      description: ''
    }
    bicycle.push(bikeObject);
  }
  
  console.log(bicycle);
}

func();
  • Related