简体   繁体   English

如何随机化我从 GET 请求中的 JSON 响应中提取的对象

[英]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.我对编码和学习 Javascript 课程非常陌生。 As part of the Requests project, I needed to pull venue information using Foursquare's API.作为请求项目的一部分,我需要使用 Foursquare 的 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:这是我的 GET 请求块:

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.我的目标是从 'items' 参数中的数组中随机化对象。 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.我建议使用Fisher-Yates shuffle 来随机化数组项。

I've used an implementation from here , thanks to the author bubnicbf感谢作者bubnicbf ,我使用了这里的实现

We'll grab the items as normal, then pass our venues array to the FisherYatesShuffle function to randomize them.我们将照常抓取项目,然后将我们的场地数组传递给 FisherYatesShuffle 函数以随机化它们。

 // 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) 最后但并非最不重要的是还有一个 lodash shuffle函数(使用 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>

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

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