Search code examples
jsondataweavemulesoft

Joining values from two arrays in DataWeave


I'm just getting started with Dataweave and trying to figure out how to transform data from this particular JSON response. I'm stumped after fairly exhaustively reading documentation and searching for examples. Can't find anything quite like it. Below is the payload I'm working with:

[
  {
    "columnMetadata": [
      {
        "name": "shape",
        "columnIndex": 0,
        "dataType": "string",
        "schemaType": "Static"
      },
      {
        "name": "color",
        "columnIndex": 1,
        "dataType": "string",
        "schemaType": "Static"
      }
    ],
    "rowData": [
      [
        "square",
        "yellow"
      ],
      [
        "circle",
        "green"
      ],
      [
        "star",
        "blue"
      ]
    ]
  }
]

The transformation I'm trying to achieve is as such:

[
    {
        "shape": "square",
        "color": "yellow"
    },
    {
        "shape": "circle",
        "color": "green"
    },
    {
        "shape": "star",
        "color": "blue"
    }
]

Any help much appreciated!


Solution

  • The way to resolve this problem is by using dynamic objects This feature allows to dynamically compose an object from other objects or array the objects in this case. It is similar to the spread operator in js.

    %dw 2.0
    output application/json
    ---
    payload flatMap ((item, index) -> do {
        var metadataNames =  item.columnMetadata map ((metadata, index) ->  metadata.name)
        ---
        item.rowData map ((datas, index) -> 
            {
                (
                    datas map ((data, index) -> 
                        {
                            (metadataNames[index]):data
                        }
                    )
                )
            }
        )
    })