使用dwl 2.0展平具有可变深度的嵌套数组

时间:2019-11-27 12:28:42

标签: dataweave mulesoft

我有以下数据:

{
  "currencyCode": "GBP",
  "type": "New",
  "orderLines": [
    {
      "currencyCode": "EUR",
      "id": "8023O000000Cc8pQAC",
      "orderLines": [
        {
          "currencyCode": "EUR",
          "id": "8023O000000Cc8qQAC",
          "parentId": "8023O000000Cc8pQAC",
          "orderLines": []
        },
        {
          "currencyCode": "EUR",
          "id": "8023O000000Cc8rQAC",
          "parentId": "8023O000000Cc8pQAC",
          "orderLines": []
        }
      ]
    },
    {
      "currencyCode": "EUR",
      "id": "8023O000000Cc8vQAC",
      "orderLines": [
        {
          "currencyCode": "EUR",
          "id": "8023O000000Cc8wQAC",
          "parentId": "8023O000000Cc8vQAC",
          "orderLines": []
        }
      ]
    }
  ]
}

注意:orderLines数组可以是任意深度

我想要这样的输出:

{
  "currencyCode": "GBP",
  "type": "New",
  "orderLines": [
    {
      "currencyCode": "EUR",
      "id": "8023O000000Cc8pQAC",
      "orderLines": []
    },
    {
        "currencyCode": "EUR",
        "id": "8023O000000Cc8qQAC",
        "parentId": "8023O000000Cc8pQAC",
        "orderLines": []
    },
    {
        "currencyCode": "EUR",
        "id": "8023O000000Cc8rQAC",
        "parentId": "8023O000000Cc8pQAC",
        "orderLines": []
    },
    {
      "currencyCode": "EUR",
      "id": "8023O000000Cc8vQAC",
      "orderLines": []
    },  
    {
      "currencyCode": "EUR",
      "id": "8023O000000Cc8wQAC",
      "parentId": "8023O000000Cc8vQAC",
      "orderLines": []
    }
  ]
}

1 个答案:

答案 0 :(得分:2)

您可以使用执行以下操作的递归函数来做到这一点:

  1. 如果级别中没有元素,则返回[]
  2. 以递归方式获取每个级别的orderLines(无子字段)
  3. 追加下一级的orderLines

像这样:

%dw 2.0
output application/json

fun getNextLevel(orders: Array) = flatten(orders.orderLines)

fun removeChildren(orders: Array) = 
    orders map ((value) -> 
        value - "orderLines"
    )

fun getOrders(orders: Array) = do {
    orders match {
        case [] -> []
        else -> removeChildren(orders) ++ getOrders(getNextLevel(orders))
    }

}
---
{
  "currencyCode": payload.currencyCode,
  "type": payload."type",
  "orderLines": getOrders(payload.orderLines)
}