user94538
user94538

Reputation: 177

Nested for loop in Mule Dataweave

%dw 1.0 %output application/json %var list1 = flowVars.var1

%var list2 = flowVars.var2

I have 2 lists list1 and list2 like below.

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"}]

how can i create list3 using list1 and list2? For each employee in list1, iterate over list2, get the title from list2 and create 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"} ]

Upvotes: 0

Views: 1528

Answers (3)

Srinivas
Srinivas

Reputation: 92

You can have a map within a map as given below

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

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

Upvotes: 0

Manik Magar
Manik Magar

Reputation: 1401

You can have your list1 and list2 anywhere like flow variables. For demonstration, I just created two variables in 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 ""
}

So -

  1. You will be iterating over list1 using map
  2. with using keyword, create a loop variable titles with value of filtered list2 for current empId
  3. ($) will include all attributes from list1
  4. Then add the title attribute using titles loop variable. To make sure it doesn't fail for non-existent records, check the size.

Upvotes: 0

user94538
user94538

Reputation: 177

Below code worked fine for me.

%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]
}

Upvotes: 1

Related Questions