Filtering based on a value inside array of object using dataweave 2.0

Below is my input JSON

{
"context": "context",
"meetings": [
    {
        "id": 123,
        "subject": "subject 123",
        "attendees": [
            {
                "type": "required",
                "emailAddress": {
                    "name": "user1",
                    "address": "user1@gmail.com"
                }
            },
            {
                "type": "required",
                "emailAddress": {
                    "name": "!user2",
                    "address": "user2@gmail.com"
                }
            }
        ]
    },
    {
        "id": 456,
        "subject": "subject 456",
        "attendees": [
            {
                "type": "required",
                "emailAddress": {
                    "name": "user3",
                    "address": "user3@gmail.com"
                }
            },
            {
                "type": "required",
                "emailAddress": {
                    "name": "user4",
                    "address": "user4@gmail.com"
                }
            }
        ]
    }
]
}

From the above JSON, First, I want to filter out the objects where name of the user starts with ! and in each resultant object, I want to add a new attribute email where email is the email of the attendee whose name starts with !. Below is my expected output:

[
{
"id": 123,
"subject": "subject 123",
"attendees": [
            {
                "type": "required",
                "emailAddress": {
                    "name": "user1",
                    "address": "user1@gmail.com"
                }
            },
            {
                "type": "required",
                "emailAddress": {
                    "name": "!user2",
                    "address": "user2@gmail.com"
                }
            }
        ],
"email" : "user2@gmail.com"
}
]

I am completely new to dataweave. can someone please help me in getting the expected output.

I tried with the below code

%dw 2.0
output application/json
---
payload.meetings filter ((item, index) -> item.attendees.emailAddress.name startsWith  "!") map (
{
  "id" : $.id,
  "subject" : $.subject,
  "attendees" : $.attendees,
  "email" : ($.attendees filter $.emailAddress.name startsWith  "!")[0].emailAddress.address
})

But it turned out to be below error :

You called the function 'startsWith' with these arguments: 
  1: Array (["user1", "user2"])
  2: String ("!")

But it expects arguments of these types:
  1: String
  2: String

4| payload.meetings filter ((item, index) -> item.attendees.emailAddress.name startsWith  "!") map (


Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)