Search code examples
dataweavemulesoftmule4mule-esb

How to select last duplicate object in array of objects in Mule 4


There is an array of duplicate objects(same id) from which last repeated object needs to be selected. Input:

{ 
    "message": [
        { 
            "name": "Abc", 
            "address":"Mumbai",
            "phone":"91-1234567891",
            "id":123
        }, 
        { 
            "name": "Pqr", 
            "address":"Pune",
            "phone":"91-1234985438",
            "id":456
        }, 
        { 
            "name": "Abc",
            "address":"Delhi",
            "phone":"91-1234567891",
            "id":123
        }
    ]
}

Expected Output:

{
  "message": [
    {
      "name": "Pqr",
      "address": "Pune",
      "phone": "91-1234985438",
      "id": 456
    },
    {
      "name": "Abc",
      "address": "Delhi",
      "phone": "91-1234567891",
      "id": 123
    }
  ]
}

In output, it should take the last repeated object values. I tried distinctBy function on id field but it picks random object from duplicates. Any help would be appreciated. Thank you.


Solution

  • You can try the following DataWeave expression:

    %dw 2.0
    output application/json
    ---
    {
        "message": payload.message groupBy ((item, index) -> item.id) 
            pluck ((value, key, index) -> value) 
                map ((item, index) -> item[sizeOf(item) - 1])
    }
    

    Input:

    { 
        "message": [
            { 
                "name": "Abc", 
                "address":"Mumbai",
                "phone":"91-1234567891",
                "id":123
            }, 
            { 
                "name": "Pqr", 
                "address":"Pune",
                "phone":"91-1234985438",
                "id":456
            }, 
            { 
                "name": "Abc",
                "address":"Delhi",
                "phone":"91-1234567891",
                "id":123
            }
        ]
    }
    

    Output:

    {
      "message": [
        {
          "name": "Abc",
          "address": "Delhi",
          "phone": "91-1234567891",
          "id": 123
        },
        {
          "name": "Pqr",
          "address": "Pune",
          "phone": "91-1234985438",
          "id": 456
        }
      ]
    }