简体   繁体   中英

Dataweave 2.0 reduce function to reduce the array of json Mule

My Input Json Looks like below:-

[{
        "eId": "123",
        "eType": "NZ",
        "value": [{
                "tId": "444"
            }, {
                "tId": "555"
            }
        ]
    }, {
        "eId": "456",
        "eType": "AU",
        "value": [{
                "tId": "666"
            }
        ]
    }
]

Expected Output Json to be like:

 [{
        "eId": "123",
        "eType": "NZ",
        "tId": "444"
    }, {
        "eId": "123",
        "eType": "NZ",
        "tId": "555"
    }, {
        "eId": "456",
        "eType": "AU",
        "tId": "666"
    }
]

I tried Transform using the reduce function like below. I am not getting expected response

%dw 2.0
output application/json
---
payload reduce ((val, acc = []) -> 
acc + {
    "id" : val.eId, "type": val.eType, "Tid": val.value map $.tId
})

Could someone please correct me where I am doing it wrong

I'll make an educated guess, because the example expected output is incomplete, that the expected output should look like:

[
  {
    "eId": "123",
    "type": "Co",
    "tId": "444"
  },
  {
    "eId": "123",
    "type": "Co",
    "tId": "555"
  }
]

Script:

%dw 2.0
output application/json
fun mapItem(i) = i.value map { eId: i.eId, "type": i.eType, tId: $.tId }
---
payload flatMap mapItem($)

Feel free to edit the question to add more details if needed.

You can try using the following dataweave expression:

%dw 2.0
output application/json
---
flatten(payload map (it1, ix1) -> 
    it1.value map (it2, ix2) -> {
        eId: it1.eId,
        eType: it1.eType,
        tId: it2.tId
    })

Try with this.

%dw 2.0
output application/json
var inp = payload
---
payload[0].value map {
    eId: inp[0].eId,
    Tid: $.tId
}

Updated solution

%dw 2.0
output application/json

---
payload flatMap ((item, index) ->  { 
     a: item.value map {
         eId:item.eId,
         eType: item.eType,
         tId: $.tId
     }}.a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM