【问题标题】:Dataweave: Merge 2 arrays based upon conditionDataweave:根据条件合并 2 个数组
【发布时间】:2021-04-22 16:41:27
【问题描述】:

我有 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 条记录。想知道是否有任何其他方法可以降低复杂性,从而加快响​​应速度。

【问题讨论】:

    标签: dataweave mule4


    【解决方案1】:

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

    【讨论】:

    • 这可以按预期工作并且速度更快。谢谢@SalimKhan
    【解决方案2】:

    如果您的数组是使用 id 排序的,那么您可以使用二分搜索来减少搜索的复杂性。

    【讨论】:

    • 你能举个例子吗?这可能会有所帮助
    • 二分搜索与问题有什么关系?以及如何在 DataWeave 中实现?
    猜你喜欢
    • 2019-08-10
    • 1970-01-01
    • 2020-07-24
    • 2017-12-30
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    相关资源
    最近更新 更多