简体   繁体   English

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

[英]Javascript how to create unique id on object that is pushed into an array

I want to push an object into an array a random amount of times and have each object have it's own unique id.我想将一个对象随机推送到一个数组中,并让每个对象都有自己的唯一 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.当我 console.log 数组时,我确实看到每个对象都有相同的键。

I have some code set up to generate a unique ID, but it doesn't seem to work.我设置了一些代码来生成唯一 ID,但它似乎不起作用。

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.我知道 for 循环正在推送相同的数据实例,这就是为什么它们都有相同的 id,但我不知道如何制作它,以便它们都有自己的。 Any suggestions?有什么建议么?

If you want to generate really unique id's, you should use uuid.如果你想生成真正唯一的 id,你应该使用 uuid。

Here is the npm package .这是 npm 包 It is fairly easy to setup and use.它相当容易设置和使用。

From the React docs for Lists and Keys :来自Lists 和 Keys的 React 文档:

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}));

simplelly call Math.floor(Math.random() * 10) on every push and use spread syntaxs在每次推送时简单地调用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) });
}

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.如果您不介意在 id 上发生随机数冲突,那么只需在构建数组时将新的随机 id 传播到您的对象中。 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 .在任何一种情况下,这都会选择从09的随机副本数。 If you want from 1 to 10 , then you will need to add 1 to the results of the Math.floor call.如果您想要从110 ,那么您需要将1添加到Math.floor调用的结果中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM