Created
February 3, 2025 17:01
-
-
Save picsoung/0616a492c1f8a679c0e426c961ead74b to your computer and use it in GitHub Desktop.
Organize typeform webhook submission in a key/value object
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 typeformPayload = inputData.typeformPayload || '{}'; | |
// Parse the JSON string to a JavaScript object | |
const parsedPayload = JSON.parse(typeformPayload); | |
// Extract form_response safely | |
const { form_response: formResponse = {} } = parsedPayload; | |
// Extract answers, hidden fields, and variables | |
const { answers = [], hidden = {}, variables = [] } = formResponse; | |
// Transform answers into a key-value object, ensuring multiple choice uses `label` | |
const organized_answers = answers.reduce((map, { field, type, ...rest }) => { | |
if (field?.ref && type in rest) { | |
if (type === "choice") { | |
map[field.ref] = rest[type]?.label; // Use label for single choice | |
} else if (type === "choices") { | |
map[field.ref] = rest[type]?.labels || []; // Use labels for multiple choice | |
} else { | |
map[field.ref] = rest[type]; // Default case for other types | |
} | |
} | |
return map; | |
}, { ...hidden }); // Initialize with hidden fields | |
// Transform variables into a key-value object | |
const organized_variables = variables.reduce((map, { key, type, ...rest }) => { | |
if (key && type in rest) { | |
map[key] = rest[type]; | |
} | |
return map; | |
}, {}); | |
// Merge everything into a single object | |
const answersObject = { | |
event_type: parsedPayload.event_type, | |
...organized_answers, | |
...organized_variables, | |
}; | |
// Prepare the output with the constructed answers object | |
output = answersObject; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment