Issue
i am new to flutter . I am trying to create new list from below list
var itemlist1=[
{"p_id": "a101", "model": "M-Plaz","price": 2500},
{"p_id": "a101", "model": "Z-Plaz","price": 3500},
{"p_id": "a102", "model": "M-Neo", "price": 1560},
{"p_id": "a102", "model": "N-Neo1","price": 3600}];
Output list should be like below
var newlist=[{"Subitems":[
{
"p_id":"a101",
"items": [
{"p_id": "a101", "model": "M-Plaz","price": 2500},
{"p_id": "a101", "model": "Z-Plaz","price": 3500}
]},{
"p_id": "a102",
"items": [
{"p_id": "a102", "model": "M-Neo", "price": 1560},
{"p_id": "a102", "model": "N-Neo1","price": 3600}
]},
]
}];
please i need help..
Solution
The below code gives you the required output.
var itemlist1 = [
{"p_id": "a101", "model": "M-Plaz", "price": 2500},
{"p_id": "a101", "model": "Z-Plaz", "price": 3500},
{"p_id": "a102", "model": "M-Neo", "price": 1560},
{"p_id": "a102", "model": "N-Neo1", "price": 3600}
];
var newlist = groupBy(itemlist1, (Map obj) => obj['p_id']);
var requiredOutput = [
{"Subitems": []}
];
newlist.forEach((k, v) => {
requiredOutput[0]["Subitems"]!.add({"p_id": k, "items": v})
});
print(requiredOutput);
Note: Add import "package:collection/collection.dart";
line in imports.
Answered By - nagendra nag
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.