extract contacts account displayname from account using High order function

Use flatMap and then map to join accounts and contacts

let values = results.accounts
    .flatMap { account in account.contacts.map { ($0, account.displayName) } }

Example

let accounts = [
    Account(accountID: "1", displayName: "A", managedByStakeholderID: nil, id: nil,
            contacts: [
                Contact(firstName: "a1", lastName: "a1", displayName: "aa1"),
                Contact(firstName: "a2", lastName: "a2", displayName: "aa2"),
            ]),
    Account(accountID: "2", displayName: "B", managedByStakeholderID: nil, id: nil,
            contacts: [
                Contact(firstName: "b", lastName: "b", displayName: "bb"),
            ])
]

yields

[(Contact: aa1, Optional(“A”)), (Contact: aa2, Optional(“A”)), (Contact: bb, Optional(“B”))]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top