You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中从变量数组提取Jeopardy项目API数据问题

问题分析与修复方案

核心问题

  1. 重复请求同一分类:randomNum仅初始化一次,循环中每次请求的都是同一个分类ID,无法获取6个不同的随机分类。
  2. 存储错误的数据类型:getCategoryIds将axios的完整响应对象存入categories,而非响应里的分类数据(res.data),导致后续无法正确读取内容。
  3. getCategory逻辑错误:categories是数组,不存在categories.data属性;未根据catId匹配对应分类,也未将API返回的线索格式化为项目需要的结构。

修复后的代码

let url = "https://jservice.io/api";
const NUM_CATEGORIES = 6;

// 目标数据结构:[{ title: "", clues: [{question, answer, showing: null}, ...] }, ...]
let categories = [];

/** 获取NUM_CATEGORIES个随机分类的ID,并获取对应分类数据 */
async function getCategoryIds() {
  // 先获取100个分类列表,从中随机选6个,避免直接随机ID可能拿到无效分类
  const categoryListRes = await axios.get(`${url}/categories?count=100`);
  const allCategories = categoryListRes.data;
  
  // 随机筛选6个不重复的分类
  const randomCats = [];
  while (randomCats.length < NUM_CATEGORIES) {
    const randomIndex = Math.floor(Math.random() * allCategories.length);
    const selectedCat = allCategories[randomIndex];
    // 避免重复选择同一分类
    if (!randomCats.some(cat => cat.id === selectedCat.id)) {
      randomCats.push(selectedCat);
    }
  }

  // 逐个获取选中分类的完整数据(包含线索)
  for (const cat of randomCats) {
    const catRes = await axios.get(`${url}/category?id=${cat.id}`);
    // 存入分类的完整数据
    categories.push(catRes.data);
  }
}

/** 根据分类ID返回格式化后的分类数据 */
function getCategory(catId) {
  // 在categories数组中找到对应ID的分类
  const targetCat = categories.find(cat => cat.id === catId);
  if (!targetCat) return null;

  // 格式化线索数据,添加showing字段
  const formattedClues = targetCat.clues.map(clue => ({
    question: clue.question,
    answer: clue.answer,
    showing: null
  }));

  return {
    title: targetCat.title,
    clues: formattedClues
  };
}

额外说明

  • 先获取100个分类再随机选择,比直接随机ID更可靠,因为jservice的分类ID并非连续的,直接随机可能请求到不存在的分类。
  • 使用find方法根据catId匹配分类,确保能准确获取目标分类数据。
  • 通过map格式化线索数组,统一添加showing: null字段,符合项目要求的数据结构。

内容的提问来源于stack exchange,提问作者Mikey K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 06:10:39