Created
April 16, 2024 08:05
-
-
Save picsoung/82c5e8d1d9693ef67b8c46a055643669 to your computer and use it in GitHub Desktop.
Code snippet to extract answers from typeform webhook payload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const extractValue = (tfAnswer) => { | |
switch (tfAnswer.type) { | |
case "choices": | |
if (tfAnswer.choices) { | |
// Multiple choices | |
let labels = tfAnswer.choices.labels || []; | |
if (tfAnswer.choices.other) { | |
labels.push(tfAnswer.choices.other); | |
} | |
return labels; // Return an array of selected labels | |
} | |
break; // Break is not strictly necessary after a return but can be used for consistency | |
case "choice": | |
if (Object.keys(tfAnswer.choice).length > 1) { | |
// Single choice | |
return tfAnswer.choice.other | |
? tfAnswer.choice.other.toString() | |
: tfAnswer.choice.label.toString(); // Return the selected label | |
} | |
break; | |
case "dropdown": | |
return tfAnswer.text; | |
break; | |
default: | |
// For any unhandled types, return null or an appropriate default value | |
return tfAnswer[tfAnswer.type]; | |
} | |
}; | |
const organizeAnswers = (form_response) => { | |
// Step 1: Create a mapping of field ID to ref | |
const fieldIdToRefMap = form_response.definition.fields.reduce( | |
(acc, field) => { | |
acc[field.id] = field.ref; | |
return acc; | |
}, | |
{} | |
); | |
// Step 2: Map each answer to its corresponding ref | |
const answersRefValueMap = form_response.answers.reduce((acc, answer) => { | |
const ref = fieldIdToRefMap[answer.field.id]; | |
const value = extractValue(answer); | |
acc[`${ref}`] = value; // Using $ref as key | |
return acc; | |
}, {}); | |
return answersRefValueMap; | |
}; | |
/* | |
const answers = organizeAnswers(form_response) | |
answers = { | |
question_ref: "answer to question 1", | |
another_q_ref: "answer to question 2" | |
... | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment