Script Snap: TypeError: Cannot read property "Question_ID" from undefined

I have a script snap which uses javascript to transform/restructure the input data. When I do this by hard coding the input data, my script works fine. The data in my hardcoded variable is exactly what I copy from the raw data input in snaplogic.

However, when I use the input doc rather than the hard coded input, my script fails with the error Cannot read property “Question_ID” from undefined.

Input to the script snap:
[{“answerText”:"-",“Question_ID”:“BOX_OR_RESIDENCE”},{“answerText”:“02/29/2000”,“Question_ID”:“DATE_OF_BIRTH”},{“answerText”:“5C_First_0912_001”,“Question_ID”:“FIRST_NAME”},{“answerText”:“F”,“Question_ID”:“GENDER”},{“answerText”:“2022”,“Question_ID”:“GRAD_YEAR”}]

Desired output:
[{“Request”:{“BOX_OR_RESIDENCE”:"-",“DATE_OF_BIRTH”:“02/29/2000”,“FIRST_NAME”:“5C_First_0912_001”,“GENDER”:“F”,“GRAD_YEAR”:“2022”}}]

This is the code in my script which is failing:
var result = {};
for (var i = 0; i < doc.length; i++) {
result[doc[i].Question_ID] = doc[i].answerText;
}

Attached is the pipeline, with a working and failing path.script.
AC105 2_TESTer_2020_09_14.slp (29.7 KB)

What am i doing wrong here with regards to the input doc?

Hi @acesario,

The doc in the OK script is array, but it is not an array in the script that falls, so you cannot access the fields in the same way. Thus, if you want to get value of Question_ID you have to use the following doc.Question_ID, or in your case it will be:
result[doc.Question_ID] = doc.answerText;

I’ve changed your script and after the changes the document in the output of the script is as follows:

Attached herewith is your pipeline with already implemented changes:
AC105 2_TESTer_2020_09_22.slp (30.1 KB)

Regards,
Lazo

2 Likes