简体   繁体   中英

How do I randomize the object I pull from the JSON Response in a GET Request

I'm very new to coding and working through a course on Javascript. As part of the Requests project, I needed to pull venue information using Foursquare's API. As it sits, it pulls from the array in order as it appears. I'm trying to randomize which venue it pulls. Here is my GET request block:

const getVenues = async () => {
  const city = $input.val();
  const urlToFetch = `${url}${city}&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20210712`;

  try {
    const response = await fetch(urlToFetch);
    if(response.ok) {
      const jsonResponse = await response.json();
      const venues = jsonResponse.response.groups[0].items.map(item => item.venue);
      console.log(jsonResponse);
      return venues;
    };
  }
  catch(error) {console.log(error)};
};

My goal is to randomize the object from the array in the 'items' parameter. I've tried setting the venues variable to

const venues = Math.floor(Math.random(jsonResponse...)*10)

but this doesn't work. Thanks

I would suggest using a Fisher-Yates shuffle to randomize array items.

I've used an implementation from here , thanks to the author bubnicbf

We'll grab the items as normal, then pass our venues array to the FisherYatesShuffle function to randomize them.

 // https://github.com/bubnicbf/Fisher-Yates-shuffle/blob/master/Fisher-Yates.js function FisherYatesShuffle(a) { var n = a.length, r, temp; while (n > 1) { r = Math.floor(n * Math.random()); n -= 1; temp = a[n]; a[n] = a[r]; a[r] = temp; } return a; } // Assign values to allow function to run... $input = { val() {} } url = '' city = '' clientId = '' clientSecret = '' const getVenues = async () => { const city = $input.val(); const urlToFetch = `${url}${city}&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20210712`; try { const response = await fetch(urlToFetch); if(response.ok) { const jsonResponse = await response.json(); const venues = jsonResponse.response.groups[0].items.map(item => item.venue); console.log('Venues (unshuffled):', venues); // Randomize our venues const shuffledVenues = FisherYatesShuffle(venues); console.log('Venues (shuffled):', shuffledVenues); return shuffledVenues; }; } catch(error) {console.log(error)}; }; // Call the service getVenues() // Mocked version of fetch, for demonstration purposes. function fetch() { const response = { ok: true, json() { return { response: { groups: [ { items: [ { venue: 'Venue 1'}, { venue: 'Venue 2'}, { venue: 'Venue 3'}, { venue: 'Venue 4'}, { venue: 'Venue 5'} ] } ] } } } } return new Promise(resolve => { setTimeout(resolve, 100, response) }) }

And a simpler demonstration is below, showing us shuffling our venues array:

 function FisherYatesShuffle(a) { var n = a.length, r, temp; while (n > 1) { r = Math.floor(n * Math.random()); n -= 1; temp = a[n]; a[n] = a[r]; a[r] = temp; } return a; } const venues = [ { venue: 'Venue 1'}, { venue: 'Venue 2'}, { venue: 'Venue 3'}, { venue: 'Venue 4'}, { venue: 'Venue 5'} ]; console.log("Venues:", venues); console.log("Venues (shuffled):", FisherYatesShuffle(venues));
And last, but not least there is a lodash shuffle function as well (that uses a version of Fisher-Yates)

 const venues = [ { venue: 'Venue 1'}, { venue: 'Venue 2'}, { venue: 'Venue 3'}, { venue: 'Venue 4'}, { venue: 'Venue 5'} ]; console.log("Venues:", venues); console.log("Venues (shuffled):", _.shuffle(venues))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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