2

I have a flat array of Customers, and could not find an appropriate Method (Way) to Unflatten it so that each Customer & his Age becomes Nested.

INPUT

{
 "1st Customer": "2216",
 "Age": "90",
 "2nd Customer": "2231",
 "Age": "90",
 "3rd Customer": "2249",
 "Age": "120",
 "4th Customer": "2302",
 "Age": "150",
 "5th Customer": "",
 "Age": ""
}

OUTPUT

{
 "customers": [
  {
   "CustomerSeq": "1",
   "CustomerID": "2216",
   "Age": 90,
  },
  {
   "CustomerSeq": "2",
   "CustomerID": "2231",
   "Age": 90,
  },
  {
   "CustomerSeq": "3",
   "CustomerID": "2249",
   "Age": 120,
  },
  {
   "CustomerSeq": "5",
   "CustomerID": "2302",
   "Age": 150,
  }
 ]
}

2 Answers2

1

There is a good function for it in Mule: divideBy. It will split an array of your values from the object, and then the requested object could be created:

%dw 2.0
var x={
 "1st Customer": "2216",
 "Age": "90",
 "2nd Customer": "2231",
 "Age": "90",
 "3rd Customer": "2249",
 "Age": "120",
 "4th Customer": "2302",
 "Age": "150",
 "5th Customer": "",
 "Age": ""
}
var keys=x pluck $$
var values=x pluck $
import * from dw::core::Arrays
output application/dw
---
values divideBy 2 map (item,index) -> 
 {
    CustomerSeq:index+1,
    CustomerID:item[0],
    Age:item[1]
 }

output

[
  {
    CustomerSeq: 1,
    CustomerID: "2216",
    Age: "90"
  }, 
  {
    CustomerSeq: 2,
    CustomerID: "2231",
    Age: "90"
  }, 
  {
    CustomerSeq: 3,
    CustomerID: "2249",
    Age: "120"
  }, 
  {
    CustomerSeq: 4,
    CustomerID: "2302",
    Age: "150"
  }, 
  {
    CustomerSeq: 5,
    CustomerID: "",
    Age: ""
  }
]
aled
  • 21,330
  • 3
  • 27
  • 34
Alex
  • 4,457
  • 2
  • 20
  • 59
1

Thanks a lot, Alex The divideBy is exactly what I was looking for

The Solution [including the removal of the empty values]:

%dw 2.0
output application/json

import * from dw::core::Objects
---
customers:
  ((payload filterObject ((value, key, index) -> value != "")) divideBy 2) map (
    (pCustomer, indexOfpCustomer) -> {
      CustomerSeq:indexOfpCustomer+1,
      CustomerID: pCustomer[0],
      Age: pCustomer[1]
    })