Zip key and value arrays into one object with Dataweave

202 views Asked by At

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?

2

There are 2 answers

2
Ray A On BEST ANSWER

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> )
}
0
Salim Khan On

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])
    }