2

I need to generate a single object starting from two arrays, one with the key names and the other with the values. I was able to get it using the following code:

var keys = ["fieldA","fieldB","fieldC"]
var values = [45,"data", {some: "object"}]
---
(keys zip values) map ((keyValueArray, index) -> 
    {
        (keyValueArray[0]):keyValueArray[1]
    }
) reduce ((singleKeyObject, acc) -> acc ++ singleKeyObject)

That code produces this output:

{
  "fieldA": 45,
  "fieldB": "data",
  "fieldC": {
    "some": "object"
  }
}

Is there any function that replace all these three steps in just one or at least less than the solution I found?

Jorge Garcia
  • 1,313
  • 8
  • 14
  • 1
    Not that I know of, but you can eliminate the `map` altogether and do just the `reduce`. – George Oct 08 '20 at 18:59
  • That would not be performant (using reduce over map) if the content in the arrays is huge.. – Salim Khan Oct 08 '20 at 19:35
  • @SalimKhan you say that using `map+reduce` is worst than just `reduce` in this case? – Jorge Garcia Oct 08 '20 at 22:54
  • 1
    it would be at par or better. reduce (being not lazy) would have to read the whole array before processing it while map (streams it) would not need that. – Salim Khan Oct 09 '20 at 05:35
  • 1
    @SalimKhan `map` may be lazy but if you need to visit every single piece of data (as in this case) `map` + `reduce` > just `reduce` perform the same. – George Oct 09 '20 at 17:16

2 Answers2

4

You don't need use zip or reduce or even concat ++.

Try this:

    %dw 2.0
    output application/json
    var keys = ["fieldA","fieldB","fieldC"]
    var value = [45,"data", {some: "object"}]
    ---
    {
        (  keys map (data,index) -> {((data):value[index])}  )
    }

The trick is that you enclosed the expression with curly bracket and parenthesis before the expression

Example:

{ 
     ( <expression> )
}
Ray A
  • 447
  • 2
  • 5
  • 1
    Dynamic elements – Salim Khan Oct 08 '20 at 22:54
  • 2
    Dynamic elements also entail iterating data, eliminating arrays, collapsing (aka concatenating) objects etc. This code looks cleaner but I wouldn't claim its more performant than using `zip` and `reduce`. – George Oct 09 '20 at 17:25
1

This would do just fine as well..

 %dw 2.0
    output application/json
    var keys = ["fieldA","fieldB","fieldC"]
    var value = [45,"data", {some: "object"}]
    ---
   {
          (keys map (data,index) -> (data):value[index])
    }
Salim Khan
  • 4,233
  • 11
  • 15