samedi 21 mars 2020

How do you skip over an array of JSON objects when randomly pulling data with fetch?

I'm creating an app that randomly pulls one of 40 objects from a JSON array in a JSON file (people.json) when a button is clicked. It works but will often pull duplicates. How would I go about skipping an object in the JSON file if that object has already been randomly called so that I can avoid duplicates?

Here is the data I have so far:

// Fetch random user and add money
async function getRandomUser() {
  const res = await fetch('people.json');
  const data = await res.json();

  let randomUser = data[Math.floor(Math.random() * data.length)];

  addData(randomUser);
}

// Add new obj to data array
function addData(obj) {
  data.push(obj);

  updateDOM();
}



Aucun commentaire:

Enregistrer un commentaire