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

如何在多维数组与一维对象中匹配ID,避免过多嵌套循环?

Optimizing ID Matching Between Nested Arrays and Objects

Hey there! I see you've got a working solution using nested map calls, but we can definitely make this more efficient—especially if your dataset grows larger. Let's break down the issues with the original approach and build a better version.

What's Less Efficient in the Original Code

  • You're looping through all keys in storedOBJ for every single question—that's a lot of redundant checks. If you have 100 pages, 10 questions per page, and 50 entries in storedOBJ, that's 50,000 extra iterations!
  • Using nested map plus manual push to build the result array works, but it's a bit clunky and harder to read at a glance.

A Faster, Cleaner Approach

Instead of checking every key in storedOBJ for each question, we can leverage object key lookups (which are O(1) time!) and use array methods that streamline the process:

const getMatchingIDs = function(pages, storedOBJ) {
  // Use flatMap to flatten nested results in one go
  return pages.flatMap(page => 
    page.questions
      // First, filter out questions that don't exist in storedOBJ (skip unnecessary work)
      .filter(question => storedOBJ.hasOwnProperty(question.questionText))
      // For matching questions, build the ID pair directly
      .map(question => {
        const answerIndex = storedOBJ[question.questionText];
        const answerID = question.answers[answerIndex].id;
        return `${question.id}:${answerID}`;
      })
  );
};

Why This Works Better

  1. O(1) Key Lookups: Instead of looping through all storedOBJ keys for each question, we just check if the question's text exists as a key, then grab the index instantly. This drops the time complexity from O(P*Q*S) to O(P*Q) (P = number of pages, Q = questions per page, S = entries in storedOBJ).
  2. flatMap for Clean Flattening: No more manually pushing to an array—flatMap handles turning nested question results into a single flat array automatically.
  3. Early Filtering: We filter out non-matching questions first, so we don't waste time processing questions that have no corresponding entry in storedOBJ.

Testing with Your Sample Data

Let's plug in your example to confirm it works:

const pages = [
  {
    questions: [
      { id: 987, questionText: 'Some Question', answers: [{ id: 154 }, { id: 232 }, { id: 312 }] },
      { id: 324, questionText: 'Another Question', answers: [{ id: 154 }, { id: 232 }, { id: 312 }] },
      { id: 467, questionText: 'Last Question', answers: [{ id: 154 }, { id: 232 }, { id: 312 }] }
    ]
  }
];
const storedOBJ = { 'Some Question': 0, 'Last Question': 0, 'Another Question': 2 };

console.log(getMatchingIDs(pages, storedOBJ)); 
// Output: ["987:154", "324:312", "467:154"] — exactly what you need!

Bonus: Add Safety Checks

If you want to handle edge cases (like invalid answer indexes), you can add a quick validation step:

.map(question => {
  const answerIndex = storedOBJ[question.questionText];
  // Make sure the index is a valid number within the answers array bounds
  if (typeof answerIndex === 'number' && answerIndex >= 0 && answerIndex < question.answers.length) {
    const answerID = question.answers[answerIndex].id;
    return `${question.id}:${answerID}`;
  }
  // Optional: Return null or skip invalid entries
  return null;
})
// Filter out any null results from invalid indexes
.filter(Boolean)

内容的提问来源于stack exchange,提问作者Jaeeun Lee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:46:56