I have an array of object.
[
{
"b": 0,
"a": 5
},
{
"b": 0,
"a": 10
},
{
"b": 0,
"a": 15
}
]
Now I want that current value of b is calculated based on sum of previous object’s "a" and "b" values.
For example, when I use map function, I will reach to first object. It will not change because it is first object. Now I will reach next object which is :{"a":10,"b":0}
So here b will be updated to 5(because for previous object "a" is 5 and "b" is 0. So sum is 5)
Now for the 3rd object which is `{"a":15,"b":0}, b should be updated to 15. Because in the previous iteration, I have updated the value of b.
My problem is DataWeave map function is taking the unupdated value of b instead of updated one. So it is producing below output:
[
{
"b": 0,
"a": 5
},
{
"b": 5,
"a": 10
},
{
"b": 10,
"a": 15
}
]
Instead this I want this output:
[
{
"b": 0,
"a": 5
},
{
"b": 5,
"a": 10
},
{
"b": 15,
"a": 15
}
]
Here is my script
%dw 2.0
output application/json
---
payload map ((item, index) -> {
b: if (index == 0) 0 else (payload[index - 1].a + payload[index - 1].b),
a: item.a
})
I don’t know how to get the updated value in every iteration. Any help would be appreciated.
>Solution :
Try the below solution
Input
[
{
"b": 0,
"a": 5
},
{
"b": 0,
"a": 10
},
{
"b": 0,
"a": 15
}
]
Dataweave Script
%dw 2.0
output application/json
---
(payload reduce ((item, acc={b: 0, arr: []}) -> {
b: if (isEmpty(acc.arr)) 0 else acc.b + acc.arr[-1].a,
a: item.a,
arr: acc.arr ++ [{ b: if (isEmpty(acc.arr)) 0 else acc.b + acc.arr[-1].a, a: item.a }]
})).arr
Output
[
{
"b": 0,
"a": 5
},
{
"b": 5,
"a": 10
},
{
"b": 15,
"a": 15
}
]