Dataweave Transformation- How can I reduce a payload array when condition is met

56 views Asked by At

I have this JSON payload:

[
    {
        "Id": "6812",
        "status": "Available",
        "expirationDate": "2024-04-30T13:00:00.000-07:00",
        "quantityOnHand": 6124
    },
    {
        "Id": "7491",
        "status": "Available",
        "expirationDate": "2024-06-29T13:00:00.000-07:00",
        "quantityOnHand": 864
    },
    {
        "NetsuiteId": "6569",
        "status": "Available",
        "expirationDate": "2100-12-12T13:00:00.000-07:00",
        "quantityOnHand": 3

    },
    {
        "Id": "6582",
        "status": "Available",
        "expirationDate": "2100-12-12T13:00:00.000-07:00",
        "quantityOnHand": 1
    }
]

I have a variable component that sets my order quantity. Basically what I want to do is return the payload items that will suffice the order quantity variable. So for example my vars.quantityOrder is 100, then my transform component will return :

{
        "Id": "6812",
        "status": "Available",
        "expirationDate": "2024-04-30T13:00:00.000-07:00",
        "quantityOnHand": 6124
    }

If it is 6500 , then it would return :

[
    {
        "Id": "6812",
        "status": "Available",
        "expirationDate": "2024-04-30T13:00:00.000-07:00",
        "quantityOnHand": 6124
    },
    {
        "Id": "7491",
        "status": "Available",
        "expirationDate": "2024-06-29T13:00:00.000-07:00",
        "quantityOnHand": 864
    }
] 

And so on.

I am very new to DataWeave and I'm not sure how I can do this. I have written up something like:

%dw 2.0
output application/json

var quantityOrder = vars.quantityOrder 

var result = payload filter ((item, index) -> quantityOrder > 0) map ((item, index) -> {
    "Id": item.Id,
    "status": item.status,
    "expirationDate": item.expirationDate,
    "quantity": item.quantityOnHand - quantityOrder

})

---
result

However this gives me syntax errors. Would appreciate any guidance or input.

1

There are 1 answers

2
aled On BEST ANSWER

It is not clear what is the issue you are having but if you are trying to get the items from the input payload where quantityOnHand > quantityOrder then the condition of your filter is incorrect. I would change it to:

%dw 2.0
output application/json

var quantityOrder = 100

var result = payload 
    filter ((item, index) -> item.quantityOnHand > quantityOrder) 
    map ((item, index) -> 
        {
            "Id": item.Id,
            "status": item.status,
            "expirationDate": item.expirationDate,
            "quantity": item.quantityOnHand - quantityOrder
        }
    )
---
result

The output for your input payload is:

[
  {
    "Id": "6812",
    "status": "Available",
    "expirationDate": "2024-04-30T13:00:00.000-07:00",
    "quantity": 6024
  },
  {
    "Id": "7491",
    "status": "Available",
    "expirationDate": "2024-06-29T13:00:00.000-07:00",
    "quantity": 764
  }
]