【发布时间】:2021-03-19 22:52:33
【问题描述】:
场景:给定如下输入 sampleArray ,我想将所有拥有特定老师的学生分组。
在 DataWeave 中,我们有一个方法 groupBy,它允许我们对指定字符串键的数组进行分组。 但是在这里,由于 item.studentsMarks.subjectTeacher 返回一个数组,我收到了下面指定的错误。
谁能帮忙。提前致谢。
下面附上预期的输出。
示例输入:
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"
}
]
}
]
代码尝试:
payload groupBy ((item, index) -> item.studentsMarks.subjectTeacher)
错误:
Cannot coerce Array to String
预期输出:
[
"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这个表达式上,因为item.studentsMarks是一个数组——因此下一个.subjectTeacher是一个与.*subjectTeacher非常相似的选择器,它返回一个数组,因此你会得到你得到的错误。 -
@George 嗨,我附上了预期的输出。我理解了这个问题,但正在寻找一种使用 groupBy 实现解决方案的方法。如果您能找到合适的方法,请告诉我。非常感谢