javascriptarray-push

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. 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?


Solution

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