[英]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.在本例中,
quantity
为 3,因此将使用newtaskconfig
object 中的其他name:value
对创建三个任务。 The quantity is used in the for loop to push that many tasks to the newtasks
array.该数量在 for 循环中用于将这么多任务推送到
newtasks
数组。 An id with a random three digit integer is then assigned to each object within the newtasks
array.然后将具有随机三位数 integer 的 id 分配给
newtasks
数组中的每个 object。
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:然后,当我将 newtasks 数组记录到控制台时,不是每个 object 都有唯一的 id,它们最终都得到完全相同的 ID,如下所示:
[
{
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?如何更改我的方法,以便为数组中的每个 object 分配一个唯一的三位数 ID?
Just change the line to newtasks.push({...newtaskconfig})
, instead of newtasks.push(newtaskconfig)
which causing have same ref.只需将行更改为
newtasks.push({...newtaskconfig})
,而不是导致具有相同引用的newtasks.push(newtaskconfig)
。
Update: as @jonrsharpe suggest, simplify the code to the following.更新:正如@jonrsharpe 建议的那样,将代码简化为以下内容。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.