Reputation: 1227
I have data like this
{
"Categories": [{
"ID": 1064,
"Name": "Pizza",
"Subcategories": [{
"ID": 87,
"CategoryID": 1064,
"CategoryName": "Pizza",
"Items": [{
"ID": 1195,
"Name": "Fajita Pizza (S)"
"IsFeatured": true,
},
{
"ID": 1196,
"Name": "Fajita Pizza (M)"
},
{
"ID": 1197,
"Name": "Fajita Pizza (L)"
}
]
},
{
"ID": 87,
"CategoryID": 1064,
"CategoryName": "Pizza",
"Items": [{
"ID": 1195,
"Name": "Fajita Pizza (S)"
},
{
"ID": 1196,
"Name": "Fajita Pizza (M)"
},
{
"ID": 1197,
"Name": "Fajita Pizza (L)"
}
]
}
]
},
{
"ID": 1064,
"Name": "Pizza",
"Subcategories": [{
"ID": 87,
"CategoryID": 1064,
"CategoryName": "Pizza",
"Items": [{
"ID": 1195,
"Name": "Fajita Pizza (S)"
"IsFeatured": true,
},
{
"ID": 1196,
"Name": "Fajita Pizza (M)"
},
{
"ID": 1197,
"Name": "Fajita Pizza (L)"
}
]
}]
},
{
"ID": 1084,
"Name": "beverages",
"Description": null,
"Image": null,
"StatusID": 1,
"LocationID": 2112,
"Subcategories": []
}
],
"description": "Success",
"status": 1
}
What I need to do is add all Items which are in Subcategories in single array. and its working fine its working like this
Future<List> dosomestuff() async {
print(WishList.wishlistArray);
http.Response res = await http.get(
'http://retailapi.airtechsolutions.pk/api/menu/2112',
);
Map<String, dynamic> map = json.decode(res.body);
if (map['description'] == "Success") {
print('show kr ');
List<dynamic> data = map["Categories"];
data.forEach((category) {
if (category['Subcategories'] != null) {
category['Subcategories'].forEach((subcategory) {
items['Items'].addAll(
subcategory['Items']
);
});
}
});
}
}
Now there is one issue now I need to add only those items whose ID is in my other array.
Othere array is this WishList.wishlistArray
the data is in array look like this
[1217, 1216, 1195, 1196, 1197]
What I need to is I need to add those Items only whose Id is in this array
Upvotes: 1
Views: 1131
Reputation: 3288
You can use .where() method of List to filter items by ID. Try this code:
final allowedItemIds = [1217, 1216, 1195, 1196, 1197];
List<dynamic> data = map["Categories"];
data.forEach((category) {
if (category['Subcategories'] != null) {
category['Subcategories'].forEach((subcategory) {
final itemsToAdd = subcategory['Items'];
final filteredItemsToAdd =
itemsToAdd.where((item) => allowedItemIds.contains(item['ID']));
items['Items'].addAll(filteredItemsToAdd);
});
}
},
);
Upvotes: 1