英文:
How to get data based on condition from nested array golang grpc service
问题
我正在尝试根据下一个数组条件获取特定数据的Go代码。我想,我只需要给一个例子来说明清楚。
假设我有一个如下的数组:
detail: {
contacts: [
{
email: "testing@gmail.com",
condition: {
valid: "Yes",
verified: "No"
}
},
{
email: "testing2@gmail.com",
condition: {
valid: "Yes",
verified: "Yes"
}
}
]
}
所以,我想在调用grpc函数后,如果条件中的verified为"Yes",则将email作为返回值。
result, err := grpcService.callingService.GetContactDetail(ctx, &contactServicePb.GetContactDetailRequest{
ContactId: "123",
})
if err != nil {
return err
}
这是我目前尝试的,我可以访问contacts列表,但我不知道如何获取属于"Yes" verified的email。
fmt.Println(result.Detail.Contacts)
输出如下所示:
{
email: "testing@gmail.com",
condition: {
valid: "Yes",
verified: "No"
}
},
{
email: "testing2@gmail.com",
condition: {
valid: "Yes",
verified: "Yes"
}
}
英文:
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"
}
}
答案1
得分: 1
你可以遍历result.Detail.Contacts
数组,并在“Yes”验证条件下存储联系人的电子邮件:
verifiedEmails := []string{}
for _, contact := range result.Detail.Contacts {
if contact.condition.verified == "Yes" {
verifiedEmails = append(verifiedEmails, contact.email)
}
}
fmt.Println(verifiedEmails)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论