Dataweave: Add a sum in an Object

Viewed 56

I want to add a sum field in an object. Here is the trivial code I did:

%dw 2.0

output application/json
fun compute(a) = a

var demo=
{
    a: compute(1),
    b: compute(2),
    c: compute(4),
    sum: compute(1)+compute(2)+compute(4)
}

---

demo

The goal is to avoid to redo multiple function calls in the sum fied. Here is the result:

{
  "a": 1,
  "b": 2,
  "c": 4,
  "sum": 7
}
1 Answers

Here is something working but I wonder if it is possible to have something better:

%dw 2.0
import * from dw::core::Objects
output application/json

fun compute(a) = a

var demo=
    using  (
        tmp= {
            a: compute(1),
            b: compute(2),
            c: compute(4),
        }
    ) tmp ++ { sum:sum(valueSet(tmp)) }


---

demo
Related