Warm tip: This article is reproduced from serverfault.com, please click

Dataweave 2.0 reduce function to reduce the array of json Mule

发布于 2020-12-16 01:45:04

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

Questioner
Infinity
Viewed
0
aled 2020-12-16 10:20:00

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.