Search code examples
javascriptnode.jstypeform

How can I enter null values on indexes where 2 arrays don't match?


I'm retrieving answers from the Typeform API. I'll put these answers into a dataset where the questions are the column names. All of this works, untill a question isn't answered. This doesn't return a null value. For example:

Questions : [A, B, C, D]

Answers: [a, c, d] -> Question B didn't receive an answer.

I expect an output of [a, null, c, d] for above example.

I tried multiple ways to implement this in my code, but I don't find the right answer.

  let surveys = formsAnswer.items.map(survey => {
    let i = 0
    let lam = survey.answers.map(ans => {
      let answ
      let rightID2 = schema.map(findID => {
        if (findID.id.toLowerCase() === req.body.id){
          let id = findID.columnID[i]
          i++
          return id
        }
      })
      switch (ans.type) {
        case 'boolean':
          answ = ans.boolean ? 'Yes' : 'No'
          break
        case 'choice':
          answ = ans.choice.label
          break
        case 'payment':
          answ = parseFloat(ans.payment.amount) * 100
          break
        case 'empty':
          answ = null
          break
        default:
          answ = ans[ans.type]
          break
      }
      return answ
    })
    return lam
  })
  return res.status(200).json(surveys)
})

In schema I have access to an array of all the question IDs from 1 form.

Thanks in advance!

EDIT 1 Example output of a survey with 10 questions.

   [
       [["ZoW7FL2pVKvR","gfds"],
        ["amx5Q2JU4Qa7","Car 1"],
        ["jlqW0xFRGXdm","No"],
        ["FhfIURjvE8nN","dfs@hotmail.com"], 
        ["vVTYmlvc1YIy",0] 
        ["DqX2Dy0cvmMy","fezfze"]],

       [["ZoW7FL2pVKvR", "Ruben"],
        ["ihNcWeYgZHPb","Male"],
        ["amx5Q2JU4Qa7","Car 2"],
        ["jlqW0xFRGXdm", "Yes"],
        ["FhfIURjvE8nN","ruben@gmail.com"],
        ["vVTYmlvc1YIy", 2],
        ["b8y0pDw3gYpn","No"],
        ["beeg0rtb7Mai","1995-02-10T00:00:00Z"],
        ["Knox8dyeM4Ak",10]]
  ]

This is the array of the all the questionIDs from 1 survey

"columnID": [
      "ZoW7FL2pVKvR",
      "ihNcWeYgZHPb",
      "amx5Q2JU4Qa7",
      "jlqW0xFRGXdm",
      "FhfIURjvE8nN",
      "vVTYmlvc1YIy",
      "b8y0pDw3gYpn",
      "beeg0rtb7Mai",
      "Knox8dyeM4Ak",
      "DqX2Dy0cvmMy"
    ]


Solution

  • I can't tell you, why the answer is not in your list, because I don't understand your code, but I might be able to help you get the array, you want.

    Assume you have an array with the ids of all questions called questionIds

    const allAnswers = questionIds.map(questionId => getAnswerForQuestionByQuestionId(questionId, answers)
    
    function getAnswerForQuestionByQuestionId(questionId, answers) {
      for(const answer of answers) {
        if (answer[0] === questionId) {
          return answer[1]
        }
      }
      return null
    }
    

    This will return the array you are looking for.