My input is
{
"value": [
{
"FirstName": "LISA",
"Sku1": 10074895,
"Sku2": 10074896,
"Sku3": 10074897
},
{
"FirstName": "JOSE",
"Sku1": 10128582,
"Sku2": null,
"Sku3": null
}
]
}
Output I want is a string concatenating all the SKUs
{
"value": [
{
"FirstName": "LISA",
"Skus": "10074895, 10074896, 10074897"
},
{
"FirstName": "JOSE",
"Skus": "10128582"
}
]
}
I'm new to Dataweave and not sure how to do this Thanks in advance
My input will have more keys than "FirstName", that I will want to exclude
{
"value": [
{
"FirstName": "LISA",
"Country": "CA",
"Sku1": 10074895,
"Sku2": 10074896,
"Sku3": 10074897
},
{
"FirstName": "JOSE",
"Country": "CA",
"Sku1": 10128582,
"Sku2": null,
"Sku3": null
}
]
}
This is the solution I have come up with, can someone help fix this solution . The problem is that there is a trailing "," at the end of "Skus" in the output
%dw 2.0
output application/json
fun mapToResponseModel(customObj) = do {
var skus = createSkus(customObj)
var withoutSkus = mapWithoutSkus(customObj)
---
withoutSkus ++ { "Skus": skus }
}
fun createSkus(customObj) =
keysOf(customObj) reduce (key, acc = "") ->
if ((key contains "Sku") and (customObj[key] != null))
customObj[key] ++ "," ++ acc
else
acc
fun mapWithoutSkus(customObj) =
customObj mapObject (value, key) ->
if (value != null and !(key contains "Sku"))
{ (key): value }
else
{}
---
{
value: payload.value map (customObj) ->
mapToResponseModel(customObj)
}
Output
{
"value": [
{
"FirstName": "LISA",
"Country": "CA",
"Skus": "10074897,10074896,10074895,"
},
{
"FirstName": "JOSE",
"Country": "CA",
"Skus": "10128582,"
}
]
}
For Edit 1 try with the following script:
%dw 2.0
output application/json
var skuValues = payload.value map {
($ filterObject (($$) contains "Sku" ) mapObject {
a : $
})
}
---
value: payload.value map {
"FirstName": $.FirstName,
"Country" : $.Country,
"Skus": skuValues [($$)] filterObject($ != null) pluck $ joinBy ","
}