How to get data based on condition from nested array golang grpc service

Issue

I’m trying to get specific data based on next array condition in Go. I think, I will just give an example to make it clear.

Let’s say I have an array like this

detail: {

   contacts: [

      {

         email: "testing@gmail.com"

         condition: {
               
              valid: "Yes",

              verified: "No"

         }

      },

      {

         email: "testing2@gmail.com"

         condition: {

              valid: "Yes",

              verified: "Yes"

         }

      }

   ]

}

So, I’m trying to get the email as a return after calling grpc function if the condition has verified "Yes" on it.

result, err := grpcService.callingService.GetContactDetail(ctx, &contactServicePb.GetContactDetailRequest{
    ContactId: "123",
})
if err != nil {
    return err
}

This is what I tried so far, I can access the contacts list but I don’t know how do I take email which belong to "Yes" verified.

fmt.Println(result.Detail.Contacts)

this is how the output looks like

      {

         email: "testing@gmail.com"

         condition: {

              valid: "Yes",

              verified: "No"

         }

      },

      {

         email: "testing2@gmail.com"

         condition: {

              valid: "Yes",

              verified: "Yes"

         }

      }

Solution

You can iterate over result.Detail.Contacts array and store contacts’ email with "Yes" verified condition:

verifiedEmails := []string{}

for _, contact := range result.Detail.Contacts {
    if contact.condition.verified == "Yes" {
        validEmails = append(validEmails, contact.email)
    }
}

fmt.Println(validEmails)

Answered By – mrazimi

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.