Issue
i have single list but i want to create new list having elements
var products=[
{"pro_id": "AZ101","quality":"top", "model": "M-Plaz","price": 22500},
{"pro_id": "AZ101","quality":"top", "model": "Z-Plaz","price": 33500},
{"pro_id": "AB102","quality":"middel", "model": "M-Neo", "price": 11560},
{"pro_id": "AB102","quality":"middel", "model": "N-Neo1","price": 13600}];
i want output result like below,
under products want.. pro_id,quality and items based on pro_id
var newlist=[{"products":[
{
"pro_id":"AZ101",
"quality":"top",
"items": [
{"pro_id": "AZ101","quality":"top", "model": "M-Plaz","price": 2500},
{"pro_id": "AZ101","quality":"top", "model": "Z-Plaz","price": 3500}
]},{
"p_id": "AB102",
"quality":"middel",
"items": [
{"pro_id": "AB102","quality":"middel", "model": "M-Neo", "price": 1560},
{"pro_id": "AB102","quality":"middel", "model": "N-Neo1","price": 3600}
]},
]
}];
How get this result.
Solution
First, I am retrieving pro_id
, then finding product based on it. You can find info on code-comment.
Run on dartPad.
void main() {
final List<Map<String, dynamic>> products = [
{"pro_id": "AZ101", "quality": "top", "model": "M-Plaz", "price": 22500},
{"pro_id": "AZ101", "quality": "top", "model": "Z-Plaz", "price": 33500},
{"pro_id": "AB102", "quality": "middel", "model": "M-Neo", "price": 11560},
{"pro_id": "AB102", "quality": "middel", "model": "N-Neo1", "price": 13600}
];
/// filter product ids
List<String> productIds = [];
List<String> qualites = [];
products.forEach((product) {
if (!productIds.contains(product['pro_id'])) {
productIds.add(product['pro_id']);
qualites.add(product['quality']);
}
});
// print(productIds.toString());
/// create a subResult that will hold List of product based on id
List<Map<String, dynamic>> subResult = [];
/// find product by id
List<Map<String, dynamic>> _getProducts(String id) {
final filterProduts =
products.where((element) => element['pro_id'] == id).toList();
// print(filterProduts);
return filterProduts;
}
for (int i = 0; i < productIds.length; i++) {
subResult.add({
"pro_id": productIds[i],
"quality": qualites[i],
"items": _getProducts(productIds[i]),
});
}
// print(subResult);
/// for finish result wrap with map and list, then can be convert to List
final List<Map<String, dynamic>> result = [
{"products": subResult}
];
print(result);
}
Answered By - Yeasin Sheikh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.