Reputation: 645
My sample payload is given below:
{
"ID": "72a6dcc0",
"SourceCode": "ABC",
"TargetCode": "DEF",
.
.
.
.
.
"Products": [
{
"ProdId": "410ef294",
"ProdDetails": {
"ProdIdentifier": "410ef294-e80b",
"DateFrom": "2019-01-01T00:00:00Z",
"DateTo": "9999-12-31T00:00:00Z",
"ProductName": "ProdA"
}
}
]
}
I need to add a new attribute called "ProdDescription" to the "Products" array so that my output looks like this:
{
"ID": "72a6dcc0",
"SourceCode": "ABC",
"TargetCode": "DEF",
.
.
.
.
.
"Products": [
{
"ProdId": "410ef294",
"ProdDetails": {
"ProdIdentifier": "410ef294-e80b",
"DateFrom": "2019-01-01T00:00:00Z",
"DateTo": "9999-12-31T00:00:00Z",
"ProductName": "ProdA",
"ProdDescription": "This is a Sample"
}
}
]
}
The payload that I have given is only a sample and it has hundreds of attributes. I only need to add a new attributes to the "Products" array and also retain the other items in the main payload. Is it possible to do a complete payload "map" and inside add a new attribute to an array using "mapobject"? I am on dataweave 1.0
Upvotes: 2
Views: 3885
Reputation: 5059
The simplest way to do this is by removing the "Product" entry using the "-" operator and later adding the new "Product" entry using "++" to append a new element into an array use the "+" operator
So what I did is a helper function that express the intention of updating a field value. This function has 3 params First the object to update, second the field name, and third a callback that is going to provide the new value and is being called with the old value.
This is my sample code
%dw 1.0
%input payload application/json
%output application/json
%function updateWith( value,fieldName, newValueProvider)
using(oldValue = value[fieldName]) (
(value - fieldName) ++ {(fieldName): newValueProvider(oldValue)}
)
---
updateWith(payload, "Products",
(products) -> (
{
"Products": products map ((item) ->
updateWith(item, "ProdDetails",
((ProdDetails) -> ProdDetails ++ {"ProdDescription": "This my new Product"})))
}
)
)
Upvotes: 2