Home > Blockchain >  dart organize list of map
dart organize list of map

Time:01-26

I have a list of map that looks like:

List<dynamic> lists = [
{"name":"SpiderMan",
 "genere":"superhero"
},
{"name":"Batman",
 "genere":"superhero"
},
{"name":"Notebook",
 "genere":"romance"
},
{"name":"Titanic",
 "genere":"romance"
}
]

And what I want to do is that I want to organize the movies into one map that has same genere, the output that I want is like:

[{romance:[  
  {"name":"Notebook",
     "genere":"romance"
    },
    {"name":"Titanic",
     "genere":"romance"
    }
]},superhero:[
 {
"name":"Notebook",
     "genere":"romance"
    },
    {"name":"Titanic",
     "genere":"romance"
    }
]]

CodePudding user response:

Use This Model

import 'dart:convert';

SubTypeM subTypeMFromJson(String str) => SubTypeM.fromJson(json.decode(str));

String subTypeMToJson(SubTypeM data) => json.encode(data.toJson());

class SubTypeM {
    SubTypeM({
        required this.romance,
        required this.superhero,
    });

    List<Romance> romance;
    List<Romance> superhero;

    factory SubTypeM.fromJson(Map<String, dynamic> json) => SubTypeM(
        romance: List<Romance>.from(json["romance"].map((x) => Romance.fromJson(x))),
        superhero: List<Romance>.from(json["superhero"].map((x) => Romance.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "romance": List<dynamic>.from(romance.map((x) => x.toJson())),
        "superhero": List<dynamic>.from(superhero.map((x) => x.toJson())),
    };
}

class Romance {
    Romance({
        required this.name,
        required this.genere,
    });

    String name;
    String genere;

    factory Romance.fromJson(Map<String, dynamic> json) => Romance(
        name: json["name"],
        genere: json["genere"],
    );

    Map<String, dynamic> toJson() => {
        "name": name,
        "genere": genere,
    };
}

You can get both together . To store data

String subTypeMToJson(SubTypeM data) => json.encode(data.toJson());

to get data list

SubTypeM subTypeMFromJson(String str) => SubTypeM.fromJson(json.decode(str));

CodePudding user response:

Using groupBy in import

"package:collection/collection.dart";

code will be '''

var lists = [
  {"name": "SpiderMan", "genere": "superhero"},
  {"name": "Batman", "genere": "superhero"},
  {"name": "Notebook", "genere": "romance"},
  {"name": "Titanic", "genere": "romance"}
];

final newMap = groupBy(lists, (Map obj) => obj['genere']);

print(newMap);

/// it will return
/* 
{superhero: [{name: SpiderMan, genere: superhero}, {name: Batman, genere: superhero}], 
 romance: [{name: Notebook, genere: romance}, {name: Titanic, genere: romance}]}
 */

'''

enter image description here

  • Related