JavaScript如何在将被推入数组的对象上创建唯一的ID

发布于 2025-02-10 10:14:54 字数 691 浏览 3 评论 0原文

我想将一个对象推入数组,然后将每个对象都具有自己的唯一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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

天煞孤星 2025-02-17 10:14:54

简单呼叫Math.floor(Math.random() * 10)在每个推送语法上

// changed let to const cause it's not re-assigned
const dataArray = [];
for (let i = 0; i < randomNum; i++) {
  // this copies the original data and overwrite key to a new randomly
  // generated key
  dataArray.push({ ...data, key: Math.floor(Math.random() * 10) });
}

simplelly call Math.floor(Math.random() * 10) on every push and use spread syntaxs

// changed let to const cause it's not re-assigned
const dataArray = [];
for (let i = 0; i < randomNum; i++) {
  // this copies the original data and overwrite key to a new randomly
  // generated key
  dataArray.push({ ...data, key: Math.floor(Math.random() * 10) });
}
时光礼记 2025-02-17 10:14:54

如果要生成真正独特的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.

尐籹人 2025-02-17 10:14:54

选择钥匙的最佳方法是使用唯一标识其兄弟姐妹中列表项目的字符串。

因此,密钥不需要随机:它们只需要在兄弟姐妹中是唯一的。因此,将普通整数用于固定密钥是可以的:

const count = Math.floor(Math.random() * 10);

const dataArray = [...new Array(count).keys()].map(key => ({...data, key}));

From the React docs for Lists and Keys:

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.

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:

const count = Math.floor(Math.random() * 10);

const dataArray = [...new Array(count).keys()].map(key => ({...data, key}));
离旧人 2025-02-17 10:14:54

如果您不介意将随机数碰撞的机会在IDS上发生碰撞,则只需在构建数组时将新的随机ID传播到对象中。我可能会这样做:

const randomCopies = (data) => [...Array (Math .floor (Math .random () * 10))] .map(() => ({
  id: Math .random() .toString(16) .slice (2), 
  ... data
}))

const data = {asylumOffice: 'AyS',  citizenship: 'h',  raceOrEthnicity: 'other',  caseOutcome: 'pending', completion: 'n', currentDate: 'f'}

console .log (randomCopies (data))
.as-console-wrapper {max-height: 100% !important; top: 0}

但是,如果这只是为了避免碰撞,那么顺序数字将更加干净,您可以做到这一点:

const seqNumber = ((n) => () => ++n) (0)

const randomCopies = (data) => [...Array (Math .floor (Math .random () * 10))] .map(() => ({
  id: seqNumber(), 
  ... data
}))

const data = {asylumOffice: 'AyS',  citizenship: 'h',  raceOrEthnicity: 'other',  caseOutcome: 'pending', completion: 'n', currentDate: 'f'}

console .log (randomCopies (data))
.as-console-wrapper {max-height: 100% !important; top: 0}

无论哪种情况,这都会选择从09的随机数量副本。如果要从110,则需要将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:

const randomCopies = (data) => [...Array (Math .floor (Math .random () * 10))] .map(() => ({
  id: Math .random() .toString(16) .slice (2), 
  ... data
}))

const data = {asylumOffice: 'AyS',  citizenship: 'h',  raceOrEthnicity: 'other',  caseOutcome: 'pending', completion: 'n', currentDate: 'f'}

console .log (randomCopies (data))
.as-console-wrapper {max-height: 100% !important; top: 0}

But if this is just to avoid collisions, then a sequential number will be cleaner, and you could do this instead:

const seqNumber = ((n) => () => ++n) (0)

const randomCopies = (data) => [...Array (Math .floor (Math .random () * 10))] .map(() => ({
  id: seqNumber(), 
  ... data
}))

const data = {asylumOffice: 'AyS',  citizenship: 'h',  raceOrEthnicity: 'other',  caseOutcome: 'pending', completion: 'n', currentDate: 'f'}

console .log (randomCopies (data))
.as-console-wrapper {max-height: 100% !important; top: 0}

In either case, this will choose a random number of copies from 0 to 9. If you want from 1 to 10, then you will need to add 1 to the results of the Math.floor call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文