如何获取对象动态值?提取动态问答键值对至数组的技术问题
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
- Start with an empty array to hold our final QA objects.
- Iterate through all keys in the original object.
- For each key that follows the
question[number]format, extract its numeric suffix (like1fromquestion1). - Check if the corresponding
answer[number]key exists in the object. - 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 thequestion[number]pattern—no false positives likequestionABCwill slip through. - Dynamic Key Support: The computed property syntax
[key]lets us retain the original dynamic key names (instead of renaming to genericquestion/answerif 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
相关产品推荐
相关产品推荐

