Search code examples
dataweave

Sorting nested array with a specific list with dataweave


Sorting an array is correct, but result is not correct with a nested array.

I tried with a simple array, output is correctly sorted.

%dw 2.0
output application/json
import indexOf from dw::core::Arrays
var sortOrder=["P_A", "P_B"]
var myInput=[
            {
                "product": "P_B",
                "price": 12
            },
            {
                "product": "P_A",
                "price": 21
            }
        ]
---
myInput orderBy( indexOf(sortOrder, $.product))

Output is:

[
  {
    "product": "P_A",
    "price": 21
  },
  {
    "product": "P_B",
    "price": 12
  }
]

But when trying with a nested array, output is not sorted at all.

%dw 2.0
output application/json
import indexOf from dw::core::Arrays
var sortOrder=["P_A", "P_B"]
var myInput=[
    {
        "command": "AZ59696",
        "products": [
            {
                "product": "P_B",
                "price": 12
            },
            {
                "product": "P_A",
                "price": 21
            }
        ]
    },
    {
        "command": "BA23122",
        "products": [
            {
                "product_ref": "P_A",
                "price": 21
            },
            {
                "product_ref": "P_B",
                "price": 12
            }
        ]
    }
]
---

myInput map ((item, index) -> item  update {
    case .item.products -> item.products orderBy( indexOf(sortOrder, $.product))
})

The output is:

[
  {
    "command": "AZV59696",
    "products": [
      {
        "product": "P_B",
        "price": 12
      },
      {
        "product": "P_A",
        "price": 21
      }
    ]
  },
  {
    "command": "BA2322",
    "products": [
      {
        "product_ref": "P_A",
        "price": 21
      },
      {
        "product_ref": "P_B",
        "price": 12
      }
    ]
  }
]

What's wrong?


Solution

  • The case expression is incorrect. There is no item key in each item of the input array, so nothing is updated. Change the case expression to point to the actual key that you want to update:

    case .products -> ...