Reputation: 144
I have a list with this data and I want to transform this in a Map<DateTime, List> with as variable for event (_id, title, date, active), ere is an example of data that I recover:
[
{
"_id":8,
"title":"Matin",
"date":"2021-08-04T00:00:00.000Z",
"active":1
},
{
"_id":9,
"title":"Après-midi",
"date":"2021-08-04T12:00:00.000Z",
"active":1
},
{
"_id":11,
"title":"Matin",
"date":"2021-08-05T00:00:00.000Z",
"active":1
},
{
"_id":12,
"title":"Après-midi",
"date":"2021-08-05T12:00:00.000Z",
"active":1
},
{
"_id":6,
"title":"Matin",
"date":"2021-08-11T00:00:00.000Z",
"active":1
},
{
"_id":7,
"title":"Après-midi",
"date":"2021-08-11T12:00:00.000Z",
"active":1
},
{
"_id":4,
"title":"Matin",
"date":"2021-08-17T00:00:00.000Z",
"active":1
},
{
"_id":10,
"title":"Matin",
"date":"2021-08-17T00:00:00.000Z",
"active":1
}
]
And in each value I have a date with year, month, day and time and I would like to group the dates without taking the hour into account, what will look like this:
"2021-08-04": [
{
"_id":8,
"title":"Matin",
"date":"2021-08-04T00:00:00.000Z",
"active":1
},
{
"_id":9,
"title":"Après-midi",
"date":"2021-08-04T12:00:00.000Z",
"active":1
}
],
"2021-08-05": [
[
{
"_id":11,
"title":"Matin",
"date":"2021-08-05T00:00:00.000Z",
"active":1
},
{
"_id":12,
"title":"Après-midi",
"date":"2021-08-05T12:00:00.000Z",
"active":1
}
]
I try to do something with Map.fromIterable but I have some error... If someone can help me thanks !
Upvotes: 1
Views: 183
Reputation: 2096
Considering that data
is the List<Map<String, Object>>
variable you listed, i.e. assuming your data is not a JSON object, I'd do:
Map<String, List<Map<String,Object>>> myTfData = {}
data.forEach(
(value) {
var myDate = value['date'] as String;
if(myTfData.containsKey(myDate)) myTfData[myDate] = [];
myTfData[myDate]!.add(value);
}
);
You'd obtain a Map<String, List<Map<String,Object>>>
object as requested.
Upvotes: 1
Reputation: 31
As you are using flutter there is a package that can handle this of stuff. https://pub.dev/packages/collection
you will need groupby.
i did something like that, idk if the api is still the same. Anyhow here is the snippet.
.map(
(List<Appointment> appointments) {
appointments.sort(
(Appointment a, Appointment b) {
if (a.appointmentdate
.difference(b.appointmentdate)
.isNegative) return -1;
return 1;
},
);
return appointments;
},
).distinct();
Upvotes: 1
Reputation: 752
I brute-forced the solution type you need. The provided solution will work for sure if the format of the date stored doesn't change.
void converter(var data) {
var req={};
for (int i = 0; i < data.length; i++) {
var date=data[i]["date"].toString().substring(0,10);
if(!req.containsKey(date))
req[date]=[];
req[date].add(data[i]);
}
print(req);
}
Upvotes: 1