jokz
jokz

Reputation: 13

How to assign a random integer to every object in an array JavaScript

Edited to include a reproducible example. When a new task is created, a quantity can be input to create multiple tasks with the same data. In this case, the quantity is 3, so three tasks will be created with the other name:value pairs within the newtaskconfig object. The quantity is used in the for loop to push that many tasks to the newtasks array. An id with a random three digit integer is then assigned to each object within the newtasks array.

newtaskconfig = {
  site: 'YeezySupply',
  findby: 'URL',
  urlorpid: 'test.com',
  useproxies: 'TRUE',
  quantity: 3
}
quantity = Number(newtaskconfig.quantity)
delete newtaskconfig.quantity
newtasks=[]
for (i = 0; i < quantity; i++)  
{ 
  newtasks.push(newtaskconfig)
}
newtasks.forEach(task=>{
  task.id=Math.floor(Math.random()*(900)+100)
})

When I then log the newtasks array to console, instead of each object having a unique id, they all end up with the exact same one, shown here:

[
  {
    site: 'YeezySupply',
    findby: 'URL',
    urlorpid: 'test.com',
    useproxies: 'TRUE',
    id: 346
  },
  {
    site: 'YeezySupply',
    findby: 'URL',
    urlorpid: 'test.com',
    useproxies: 'TRUE',
    id: 346
  },
  {
    site: 'YeezySupply',
    findby: 'URL',
    urlorpid: 'test.com',
    useproxies: 'TRUE',
    id: 346
  }
]

How can I change my approach so that each object within the array is assigned a unique three digit id?

Upvotes: 0

Views: 70

Answers (1)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Just change the line to newtasks.push({...newtaskconfig}), instead of newtasks.push(newtaskconfig) which causing have same ref.

Update: as @jonrsharpe suggest, simplify the code to the following.

newtaskconfig = {
  site: "YeezySupply",
  findby: "URL",
  urlorpid: "test.com",
  useproxies: "TRUE",
  quantity: 3
};

const { quantity, ...rest } = newtaskconfig;
const newtasks = new Array(quantity)
  .fill(0)
  .map(() => ({ ...rest, id: Math.floor(Math.random() * 900 + 100) }));

console.log(newtasks);

Upvotes: 1

Related Questions