Skip to main content
Rizwanul Shaikh ha fatto una domanda in #MuleSoft DataWeave

INPUT :

use case :

-Need to check if the KEY field is present in the cpo object .

-IF key is not present in cpo object then add that key with VAL in the array or add key with empty array if VAL == NULL

-IF the key is already present in the cpo object then need to update that key array by adding VAL value in existing array in cpo object.

 

I have written the data weave code to achive that but if key is present in cpo object the instead of update the existing key array i am removing existing one and adding new one .

 

CAN any one help me to update the key array without removing and adding new key in cpo object.

 

INPUT :

[{

"id":"123",

"cpo":{

"disney":["payment"],

"code":["ISO"]

},

"ts":"123221",

"souceCode":"IMPAC",

"KEY":"add",

"VAL": "CHECK"

},

{

"id":"443",

"cpo":{

"disney":["payment"],

"product":["ACH"]

},

"ts":"56678",

"souceCode":"IDS",

"KEY":"disney",

"VAL":"PAC"

},

{

"id":"6753",

"cpo":{

"subproduct":["ACH_ORG"],

"code":["ISO"]

},

"ts":"00098",

"souceCode":"ZBA",

"KEY":"code",

"VAL":"OOD"

}]

DATAWEAVE:

 

%dw 2.0

output application/json

fun prcheck(cpo,data1,data2)=

 

if((keysOf(cpo) contains(data1 as Key)) != true)

cpo ++ (if (data2 == null) (data1):[] else (data1):[data2])

else if ((keysOf(cpo) contains(data1 as Key)))

(cpo - (data1)) ++ (data1):(cpo[data1] ++ [data2])

else cpo

---

payload map((a,a_ind)->{

id: a.id,

cpoServices: prcheck(a.cpo,a.KEY, a.VAL),

ts:a.ts,

sourceCode:a.souceCode

})

 

EXPECTED OUTPUT:

 

[

{

"id": "123",

"cpoServices": {

"disney": [

"payment"

],

"code": [

"ISO"

],

"add": [

"CHECK"

]

},

"ts": "123221",

"sourceCode": "IMPAC"

},

{

"id": "443",

"cpoServices": {

"disney": [

"payment",

"PAC"

],

"product": [

"ACH"

]

},

"ts": "56678",

"sourceCode": "IDS"

},

{

"id": "6753",

"cpoServices": {

"subproduct": [

"ACH_ORG"

],

"code": [

"ISO",

"OOD"

]

},

"ts": "00098",

"sourceCode": "ZBA"

}

]

7 risposte
  1. 10 nov 2023, 03:05

    Try this:

     

    %dw 2.0

    var a= { "id":"1" , "cpoService":"finance", "name": "madan" }

     

    var b= [

     

    { "id": 0, "name": "John" },

     

    { "id": 2, "name": "Jane" },

     

    { "id": 1, "name": "Bob" }

     

    ]

    output application/json

    ---

     

    b map ((item, index) ->

    if(item.id ~= a.id)

    a update {

    case .id -> item.id

    }

    else item

    )

    Hope this helps...