Dataweave:根据条件合并 2 个数组

Sat*_*sal 0 dataweave mule4

我有 2 个数组存储在变量中

变量.array1

[
    {
        "id": 123,
        "name": "Sam",
        "class": "first"
    },
    {
        "id": 124,
        "name": "John",
        "class": "first"
    },
    {
        "id": 125,
        "name": "Max",
        "class": "second"
    }
]
Run Code Online (Sandbox Code Playgroud)

变量.array2

[
    {
        "studentId": 123,
        "course": "science",
        "otherActivities": "sports"
    },
    {
        "studentId": 125,
        "course": "arts",
        "otherActivities": "studentCouncil"
    },
    {
        "studentId": 126,
        "course": "literature",
        "otherActivities": "drama"
    }
]
Run Code Online (Sandbox Code Playgroud)

预期输出:

[
    {
        "id": 123,
        "name": "Sam",
        "class": "first",
        "course": "science",
        "otherActivities": "sports"
    },
    {
        "id": 125,
        "name": "Max",
        "class": "second",
        "course": "arts",
        "otherActivities": "studentCouncil"
    }
]
Run Code Online (Sandbox Code Playgroud)

原始数组包含大约 5000 个。

现在,我正在使用这个作为解决方案,

//this code is inside 'for each' with collection as vars.array1
//vars.array3 is inilialised as [] before 'for each'
%dw 2.0
output application/json
---
if(sizeOf(vars.array2 filter $["studentId"] == payload.id) > 0)
(vars.array3 << (payload ++ (vars.array2 filter $["studentId"] == payload.id)[0]))
else vars.array3
Run Code Online (Sandbox Code Playgroud)

这对于大约 500 条记录来说效果很好,但对于 5k 条记录则需要时间。想知道是否有其他方法可以降低复杂性,从而提供更快的响应。

小智 5

您尝试过使用join吗?

脚本

%dw 2.0
output application/json
import * from dw::core::Arrays
var array1=[
    {
        "id": 123,
        "name": "Sam",
        "class": "first"
    },
    {
        "id": 124,
        "name": "John",
        "class": "first"
    },
    {
        "id": 125,
        "name": "Max",
        "class": "second"
    }
]
var array2=[
    {
        "studentId": 123,
        "course": "science",
        "otherActivities": "sports"
    },
    {
        "studentId": 125,
        "course": "arts",
        "otherActivities": "studentCouncil"
    },
    {
        "studentId": 126,
        "course": "literature",
        "otherActivities": "drama"
    }
]
---
join(array1, array2, (a1) -> a1.id, (a2) -> a2.studentId) map {
     ($.l ++ $.r - "studentId" )
}
Run Code Online (Sandbox Code Playgroud)