Skip to main content
Rizwanul Shaikh 님이 #MuleSoft DataWeave에 질문했습니다

UseCase : I have one Input1 payload which I am iterating through for each loop .

Input1:

[{

"id": "123",

"name": "madan"

},

{

"id": "126",

"name": "John"

},

{

"id": "123",

"dep": "Dev"

}]

I have created a variable with empty Array .Initially array will be initialized to Arr = []

now after some ForEach iteration Arr

{

"id": "123",

"name": "madan",

"anaID":"433"

},

{

"id": "126",

"name": "John",

"anaID":"434"

}

]

for each Input1 record I am checking if (Arr contains input1.id) then I need to update that same id record with below object present in Arr without duplication.

 

Expected Output:

Same Array a Arr with updated values

[{

"id": "123",

"cpoService": "finance",

"name": "madan",

"dep": "Dev",

"anaID":"433"

},

{

"id": "126",

"name": "John",

"anaID":"434"

}]

 

Can anyone help me on this how can i update the record with same id in the array.

 

@Manish Yadav​ 

@Shyam Raj Prasad​ 

@Jitender Mehta​ 

답변 9개
  1. 2023년 11월 10일 오전 2:52

    Hi @Rizwan Shaikh​ ,

     

    It looks like you need something like:

    Hi @Rizwan Shaikh​ , It looks like you need something like:%dw 2.

    %dw 2.0

    output application/json

     

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

     

    var b= [

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

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

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

    ]

     

    ---

    b map ((item, index) ->

    if(item.id ~= a.id)

    a

    else

    item

    )

    If you check the script, it's a very simple iteration of the array. When the item Id matches the object a Id, then it will replace the occurrence.

    Trick here is that we are doing a comparison of two different types, a String in the object a, and a number in the elements of the array. Having said that, we need to use "~=" to compare different types. More data in : https://developer.mulesoft.com/tutorials-and-howtos/dataweave/how-to-compare-data-types/#:~:text=The%20!%3D,Key%20%2C%20for%20example.

     

    Hope it helps.

     

    Good luck!

    Juan Cruz Basso

0/9000