JavaScript如何在将被推入数组的对象上创建唯一的ID
我想将一个对象推入数组,然后将每个对象都具有自己的唯一ID。目前,我能够将该对象推入数组,但要使“每个孩子”中的每个孩子都具有唯一的“密钥” prop”。错误。当我安装阵列时,我确实看到每个对象都有相同的键。
我设置了一些代码来生成唯一的ID,但似乎不起作用。
这是我正在调用的数据对象:
let id = Math.random().toString(16).slice(2);
export const data = {
key: id,
asylumOffice: 'AyS',
citizenship: 'h',
raceOrEthnicity: 'other',
caseOutcome: 'pending',
completion: 'n',
currentDate: 'f',
};
以及我在调用它并生成随机数量的代码:
let dataArray = [];
let randomNum = Math.floor(Math.random() * 10);
for (let i = 0; i < randomNum; i++) {
dataArray.push(data);
}
我知道for循环正在推动数据的相同实例,这就是为什么它们都具有相同的ID,但是我不喜欢知道如何做到这一点,以便每个人都有自己的。有什么建议吗?
I want to push an object into an array a random amount of times and have each object have it's own unique id. Currently, I am able to push that object into the array a random amount of times but am getting "Each child in a list should have a unique "key" prop." error. When I console.log the array, I do see that every object has the same key.
I have some code set up to generate a unique ID, but it doesn't seem to work.
Here is my data object that I am calling:
let id = Math.random().toString(16).slice(2);
export const data = {
key: id,
asylumOffice: 'AyS',
citizenship: 'h',
raceOrEthnicity: 'other',
caseOutcome: 'pending',
completion: 'n',
currentDate: 'f',
};
And the code where I am calling it and generating a random amount:
let dataArray = [];
let randomNum = Math.floor(Math.random() * 10);
for (let i = 0; i < randomNum; i++) {
dataArray.push(data);
}
I understand that the for loop is pushing the same instance of data and that's why they all have the same id, but I don't know how to make it so that they each have their own. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简单呼叫
Math.floor(Math.random() * 10)
在每个推送语法上simplelly call
Math.floor(Math.random() * 10)
on every push and use spread syntaxs如果要生成真正独特的ID,则应使用UUID。
这是NPM软件包。它很容易设置和使用。
If you want to generate really unique id’s, you should use uuid.
Here is the npm package. It is fairly easy to setup and use.
从
因此,密钥不需要随机:它们只需要在兄弟姐妹中是唯一的。因此,将普通整数用于固定密钥是可以的:
From the React docs for Lists and Keys:
So keys don't need to be random: they just need to be unique amongst siblings. And for that reason, using a plain integer for a fixed key is just fine:
如果您不介意将随机数碰撞的机会在IDS上发生碰撞,则只需在构建数组时将新的随机ID传播到对象中。我可能会这样做:
但是,如果这只是为了避免碰撞,那么顺序数字将更加干净,您可以做到这一点:
无论哪种情况,这都会选择从
0
到9
的随机数量副本。如果要从1
到10
,则需要将1
添加到Math.floor 致电。
If you don't mind taking the chance of random number collision on the ids, then just spread new random ids into your objects as you build the array. I might do it like this:
But if this is just to avoid collisions, then a sequential number will be cleaner, and you could do this instead:
In either case, this will choose a random number of copies from
0
to9
. If you want from1
to10
, then you will need to add1
to the results of theMath.floor
call.