2

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 Answers1

5

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
  • 1
    If `a` `b` and `c` are dynamic I think that your solution is perfect. I prefer the use of `do` instead of `using` but that is something personal – machaval Dec 02 '20 at 13:36
  • I think you could also use `valuesOf` instead of `valueSet` and avoid the import – maddestroyer7 Dec 03 '20 at 13:48