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

如何获取对象动态值?提取动态问答键值对至数组的技术问题

Solution for Dynamically Grouping Question/Answer Pairs in JavaScript

Got it, let's tackle this problem step by step! The core challenge here is handling those dynamic questionN and answerN keys without hardcoding each pair. Here's a straightforward approach that works no matter how many QA pairs you have:

Step-by-Step Approach

  1. Start with an empty array to hold our final QA objects.
  2. Iterate through all keys in the original object.
  3. For each key that follows the question[number] format, extract its numeric suffix (like 1 from question1).
  4. Check if the corresponding answer[number] key exists in the object.
  5. If it does, create a new object with both the question and answer, then push it to our array.

Working Code Example

var object = { 
  id:101, 
  question1: "First question", 
  answer1: "First answer", 
  question2: "Second question", 
  answer2: "Second answer", 
  age: "5 hours" 
};
var qa = [];

// Grab all keys from the original object
const allKeys = Object.keys(object);

allKeys.forEach(key => {
  // Use regex to precisely match keys like "question1", "question10", etc.
  const questionMatch = key.match(/^question(\d+)$/);
  if (questionMatch) {
    const suffix = questionMatch[1]; // Extract the number from the question key
    const answerKey = `answer${suffix}`;
    
    // Only add the pair if the corresponding answer exists to avoid gaps
    if (object.hasOwnProperty(answerKey)) {
      qa.push({
        [key]: object[key],
        [answerKey]: object[answerKey]
      });
    }
  }
});

console.log(qa);
// Output: 
// [
//   { question1: "First question", answer1: "First answer" },
//   { question2: "Second question", answer2: "Second answer" }
// ]

Why This Works

  • Precise Matching: The regex /^question(\d+)$/ ensures we only target keys that strictly follow the question[number] pattern—no false positives like questionABC will slip through.
  • Dynamic Key Support: The computed property syntax [key] lets us retain the original dynamic key names (instead of renaming to generic question/answer if you need to preserve the numbering).
  • Safety Check: object.hasOwnProperty(answerKey) prevents adding incomplete pairs if an answer is missing for a given question.

If you prefer a more concise version, you can use Array.reduce() to build the QA array in one pass:

var qa = Object.keys(object).reduce((acc, key) => {
  const match = key.match(/^question(\d+)$/);
  if (match && object[`answer${match[1]}`]) {
    acc.push({
      [key]: object[key],
      [`answer${match[1]}`]: object[`answer${match[1]}`]
    });
  }
  return acc;
}, []);

Either approach will automatically handle any number of dynamic questionN/answerN pairs, so you don't have to update your code as new pairs are added.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:32:28