Search code examples
arraysobjectmuledataweavemulesoft

How to get values from object as an array


We need to convert the object to an Array of objects and do map on the field but the field is incremental like field1, field2 which is where we got stuck. I tried the below code:

output application/json
---
payload.main.field map(value) -> {
 "name": value.name,
 "age": value.age,
 "location": value.location[0].country
}

Input:

{
  "main": {
    "field1": {
      "name": "value",
      "age": 20,
      "address": {
        "location": [
          {
            "country": "US",
            "zipcode": 1234
          },
          {
            "country": "US",
            "zipcode": 1234
          }
        ]
      }
    },
    "field2": {
      "name": "pqr",
      "age": 23,
      "address": {
        "location": [
          {
            "country": "CA",
            "zipcode": 1235
          },
          {
            "country": "US",
            "zipcode": 1234
          }
        ]
      }
    },
    "field3": {
      "name": "abc",
      "age": 22,
      "address": {
        "location": [
          {
            "country": "BU",
            "zipcode": 1236
          },
          {
            "country": "US",
            "zipcode": 1234
          }
        ]
      }
    }
  }
}

For the above Input, Below is the expected response.

Expected Output:

{
 "main": [
    {
    "name": "value",
    "age": 20
    "location": "US"
    },
    {
    "name": "pqr",
    "age": 23
    "location": "CA"
    },
    {
    "name": "abc",
    "age": 22
    "location": "BU"
    }
    ]
}

For location, it will be like location[0].country when the array size is not 0 and country not null.


Solution

  • output application/json
    ---
    
        main : payload.main pluck $ map {
                "name": $.name,
                "age": $.age,
                "location": if( sizeOf($.address.location) !=0) $.address.location[0].country else "N/A"
    }