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
Hi @Rizwan Shaikh ,
It looks like you need something like:
%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