Search code examples
mulemule4

How to transform object to array of objects with special rules in DW?


I need to transform an object that looks like this:

    {
    myKey: 'abc',
    att1:'val1',
    att2:'val2',
    ,,,
    attN: 'valN' 
    }

to

[
 {myKey: 'abc', att1:'val1'},
 {myKey: 'abc', att2:'val2'},
...
 {myKey: 'abc', attN:'valN'}
]

In other words, I need to form a pair of the attribute "myKey" with all other attributes of the object and present the result as an array.

The names of the other attributes are not fixed and can be any string other than "myKey".


Solution

  • You can convert the key-values of an object to an array using the pluck() function. Removing the key myKey gives you a list of the att* key-values. Mapping this list you can get the expected result.

    Example:

    %dw 2.0
    output application/json
    var in={
        myKey: 'abc',
        att1:'val1',
        att2:'val2',
        att3:'val3'
        }
    
    ---
    (in - "myKey") pluck {myKey: in.myKey,($$):$} 
    

    Output

    [
      {
        "myKey": "abc",
        "att1": "val1"
      },
      {
        "myKey": "abc",
        "att2": "val2"
      },
      {
        "myKey": "abc",
        "att3": "val3"
      }
    ]