1

I am getting below JSON request

[{
"Weight": "787.00",
"Volume": "65.00",
"TrackID": "128260490",
"item": [
  {
    "Description": "basketball",
    "totalquantity": 1
  },
  {
    "Description": "football",
    "totalquantity": 4
  }
  ]
 },
 {
"Weight": "68.200",
"Volume": "44.298",
"TrackID": "890433466",
"item": [
  {
    "Description": "hockeystick",
    "totalquantity": 8
  }
  ]
 }
]

and I am looking output (in json format only) in below manner:

    { 
     Purchasedetails: [
     {
     "TrackID": 128260490,
    "Description": "basketball",
     "totalquantity": 1
     },
    {
     "TrackID": 128260490,
     "Description": "football",
    "totalquantity": 4
     },
    {
    "TrackID": 890433466,
    "Description": "hockeystick",
    "totalquantity": 8
    }
   ]
}

Here if you see closely same tracking id is coming in basketball and football (description) as they have common TrackID, how can I handle this TrackID logic?

1 Answer 1

2

Try this:

%dw 2.0
output application/json
---
// Create the object with the PurchaseDetails field
{
    // Iterate over every single object in the array
    // NOTE: I prefare reduce because it saves iterations and/or array removals
    PurchaseDetails: payload reduce (  
        (pd, result=[]) -> (
            // Append the array of items with the TrackID to the result
            result ++ (
                // Build a new object for each object in the item array
                pd.item map { 
                    // Add the TrackID to the resulting object
                    TrackID: pd.TrackID,
                    ($)
                }
            )
        )
    )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.