Reputation: 139
I have a list of IDs. Also I have an object that has arrays of datas like the below structure.
[
foods(
foodId: 345,
category: 10,
tools: [10],
name: "food name 1"
),
foods(
foodId: 191,
category: 4,
tools: [2],
name: "food name 2"
),
]
In my list I have list [345, 191]
I want to have a mechanism to access the information of the object when I provide a foodId
.
I made it work with one inner and one outer loop. But I was wondering if there is an easier way to do it:
ForEach(foodDetails, id: \.self){ item in
ForEach(self.foods.datas){ ex in
if(ex.foodId == item){
Text(ex.name)
}
}
Any idea how to make it work?
Thanks in advance
Upvotes: 2
Views: 336
Reputation: 14397
you can do simply by getting first element where id match
let result = foodDetails.first(where: {$0.foodId == id})
if let food = result {
print(food.name ?? "") //if name is optional
print(food.foodId)
print(food.category)
}
result you got is that foods? optional struct which have this id
Upvotes: 1