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

Dataweave: Merge 2 arrays based upon condition

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

vars.array1

[
    {
        "id": 123,
        "name": "Sam",
        "class": "first"
    },
    {
        "id": 124,
        "name": "John",
        "class": "first"
    },
    {
        "id": 125,
        "name": "Max",
        "class": "second"
    }
]

vars.array2

[
    {
        "studentId": 123,
        "course": "science",
        "otherActivities": "sports"
    },
    {
        "studentId": 125,
        "course": "arts",
        "otherActivities": "studentCouncil"
    },
    {
        "studentId": 126,
        "course": "literature",
        "otherActivities": "drama"
    }
]

预期输出:

[
    {
        "id": 123,
        "name": "Sam",
        "class": "first",
        "course": "science",
        "otherActivities": "sports"
    },
    {
        "id": 125,
        "name": "Max",
        "class": "second",
        "course": "arts",
        "otherActivities": "studentCouncil"
    }
]

原始数组包含大约 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

这适用于大约 500 条记录,但需要时间 5k 条记录。想知道是否有任何其他方法可以降低复杂性从而提供更快的响应。

如果您的数组是使用 id 排序的,那么您可以使用二进制搜索来降低搜索的复杂性。

您尝试过使用 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" )
}