Here's how the incoming data arrives:
let e = {"authMode":"FULL","namedValues":{"Question 1":["Answer question 1"],"Question 2":["Answer question 2"],"Question 3.":["Answer Question 3"]}}
This should look like this:
[
["Question 1", "Question 2", "Question 3"],
["Answer question 1", "Answer question 2", "Answer question 3"]
]
I'll be working on getting the headers to match the destination sheet column headers and, therefore, the object above would need to be converted to a similar format.
How can this be done using Google Apps Script? I've seen some example, but none found on this one precisely.
Thank you!
CodePudding user response:
Is this something like that ?
const e = { "authMode": "FULL", "namedValues": { "Question 1": ["Answer question 1"], "Question 2": ["Answer question 2"], "Question 3.": ["Answer Question 3"] } }
const res = Object.entries(e.namedValues).reduce((acc, [questionNumber, answer]) => {
acc[0].push(questionNumber)
// spread answer because answer is an array
acc[1].push(...answer)
return acc
}, [[], []])
or a more compact way less comprehensible maybe
const res = Object.entries(e.namedValues).reduce((acc, [questionNumber, answer]) => [[...acc[0], questionNumber],[...acc[1], ...answer]] ,[[],[]]))
CodePudding user response:
This will work even if you have edited the form
Editing the form often cause the number of available answers to a given question to grow.
function onMyForm(e) {
const arr = Object.keys(e.namedValues).reduce((a,c) => {
if(c && c.length > 0 && !a.hasOwnProperty(c)) {
a[1].push(e.namedValues[c][e.namedValues[c].length - 1]);
a[0].push(c);
}
return a;
},[[],[]])
return arr;
}