在Mule Dataweave中嵌套for循环

时间:2016-11-08 18:27:04

标签: mule dataweave

%dw 1.0 %输出应用程序/ json %var list1 = flowVars.var1

%var list2 = flowVars.var2

我有2个列表list1和list2,如下所示。

list1 = [{"empId": "123", "firstName":"John", "lastName":"Doe"},
         {"empId": "456", "firstName":"Anna", "lastName":"Smith"},
         {"empId" : "567", "firstName":"Peter", "lastName":"Jones"}]

list2 = [{"empId": "567", "title":"developer"},
         {"empId": "123", "title":"tester"},
         {"empId": "456", "title":"manager"}]

如何使用list1和list2创建list3?对于list1中的每个雇员,迭代list2,从list2获取标题并创建list3。

list3 = [{"empId" : "123", "firstName":"John", "lastName":"Doe",
          "title" : "tester"}, 
         {"empId" : "456", "firstName":"Anna", "lastName":"Smith",
          "title" : "manager"} ,  
         {"empId" : "567", "firstName":"Peter", "lastName":"Jones",
          "title" : "developer"} ]

3 个答案:

答案 0 :(得分:1)

下面的代码对我来说很好。

%dw 1.0
%output application/json


%var dataLookup = {(flowVars.list2 map {
        ($.empId): $.title
     })}


---
payload map {
    empId : flowVars.list1[$$].empId,
    firstName : flowVars.list1[$$].firstName,
    lastName: flowVars.list1[$$].lastName,
    title : dataLookup[$.empId]
}

答案 1 :(得分:0)

您可以将list1和list2放在流变量的任何位置。为了演示,我刚刚在DW中创建了两个变量。

%dw 1.0
%output application/java
%var list1 = [{"empId": "123", "firstName":"John", "lastName":"Doe"},
         {"empId": "456", "firstName":"Anna", "lastName":"Smith"},
         {"empId" : "567", "firstName":"Peter", "lastName":"Jones"}]
%var list2 = [{"empId": "567", "title":"developer"},
         {"empId": "123", "title":"tester"},
         {"empId": "456", "title":"manager"}]
---
list1 map using (titles = list2 filter ((item) -> (item.empId == $.empId))) {
    ($),
    title: titles[0].title when (sizeOf titles) > 0 otherwise ""
}

所以 -

  1. 您将使用map
  2. 在list1上进行迭代
  3. 使用using关键字,为当前titles
  4. 创建一个循环变量empId,其值为已过滤的list2
  5. ($)将包含list1
  6. 中的所有属性
  7. 然后使用titles循环变量添加title属性。要确保它不会因不存在的记录而失败,请检查大小。

答案 2 :(得分:0)

您可以在地图中找到地图,如下所示

{
node1: (payload map                     
            {
            empname: $.column_0,
            empid: $.column_1

            ( flowvar.payload1 map ({
node1:
{
  deptid: $.column_0,
  deptname: $.column_1,
}
}