Scenario : Given an input as below sampleArray
, I will like to group all the students having a specific teacher.
In DataWeave we have a method groupBy that allows us to group arrays specifying a string key. But here since item.studentsMarks.subjectTeacher returns an array I am getting an error specified below.
Can anyone please help. Thanks in Advance.
Attached below is expected output.
Sample Input:
var sampleArray = [
{
"studentName" : "ABC",
"studentsMarks" : [
{
"subject" : "maths",
"marks" : "50",
"subjectTeacher" : "teacher_1"
},
{
"subject" : "science",
"marks" : "30",
"subjectTeacher" : "teacher_3"
}
]
},
{
"studentName" : "XYZ",
"studentsMarks" : [
{
"subject" : "maths",
"marks" : "90",
"subjectTeacher" : "teacher_1"
},
{
"subject" : "arts",
"marks" : "50",
"subjectTeacher" : "teacher_2"
}
]
}
]
Code tried:
payload groupBy ((item, index) -> item.studentsMarks.subjectTeacher)
Error:
Cannot coerce Array to String
Expected Output :
[
"teacher_1" : [{
"studentName" : "ABC",
"studentsMarks" : [
{
"subject" : "maths",
"marks" : "50",
"subjectTeacher" : "teacher_1"
},
{
"subject" : "science",
"marks" : "30",
"subjectTeacher" : "teacher_3"
}
]
},
{
"studentName" : "XYZ",
"studentsMarks" : [
{
"subject" : "maths",
"marks" : "90",
"subjectTeacher" : "teacher_1"
},
{
"subject" : "arts",
"marks" : "50",
"subjectTeacher" : "teacher_2"
}
]
}
],
"teacher_2" : [
{
"studentName" : "XYZ",
"studentsMarks" : [
{
"subject" : "maths",
"marks" : "90",
"subjectTeacher" : "teacher_1"
},
{
"subject" : "arts",
"marks" : "50",
"subjectTeacher" : "teacher_2"
}
]
}
],
"teacher_3" : [
{
"studentName" : "ABC",
"studentsMarks" : [
{
"subject" : "maths",
"marks" : "50",
"subjectTeacher" : "teacher_1"
},
{
"subject" : "science",
"marks" : "30",
"subjectTeacher" : "teacher_3"
}
]
}
]
]
item.studentsMarks.subjectTeacher
becauseitem.studentsMarks
is an array--as such the next.subjectTeacher
is a selector very similar to.*subjectTeacher
, which returns an array, hence why you get the error you get. – George