Search code examples
dataweavemulesoftmule-esb

How to order by attribute name?


Need a bit help with sorting attributes inside of element of array. so I have such payload:

person=[
 {
   "Phone" : "1234",
   "Name" : "John",
   "Address": "ABC"
 },
 {
   "Phone" : "5678",
   "Name" : "Mary",
   "Address": "DEF"
 },
]

and I expecting to got it like this:

 person=[
 {
   "Address": "ABC",
   "Name" : "John",
   "Phone" : "1234"
 },
 {
   "Address": "DEF",
   "Name" : "Mary",
   "Phone" : "5678"
 },
]

I try as that:

%dw 1.0
%output application/json
---
"result": payload[0] orderBy $$

but its not sorted, if I try to use

orderBy $

I got error: You cannot compare a value if type ::object...


Solution

  • You need to map each element, then order each one:

    %dw 1.0
    %output application/json
    ---
    "result": payload map ($ orderBy $$)
    

    Output:

    {
      "result": [
        {
          "Address": "ABC",
          "Name": "John",
          "Phone": "1234"
        },
        {
          "Address": "DEF",
          "Name": "Mary",
          "Phone": "5678"
        }
      ]
    }