Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter and manipulate a map

It’s the first time I use Dart and I’m stuck with a simple thing.

I have a simple Map and I need to remove some items from this map and modify the content.

I have this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  Map<String, List<String>> dataset = {
    'apple': ['apple1', 'apple2', 'apple3'],
    'pear': ['pear1', 'pear2'],
    'ananas': ['ananas1', 'ananas2', 'ananas3'],
    'orange': ['orange1', 'orange2', 'orange3', 'orange4'],
  };
  List<Map<dynamic, String>> fruits = [
    {'key': 'pear', 'labelToShow': 'Pear fruit'},
    {'key': 'ananas', 'labelToShow': 'My ananas'},
  ];

and I would like to have this:

  Map<String, Map<String, List<String>>> result = {
    'pear': {
      'values': ['pear1', 'pear2'],
      'labelToShow': 'Pear fruit'
    },
    'ananas': {
      'values': ['ananas1', 'ananas2', 'ananas3'],
      'labelToShow': 'My ananas'
    },
  };

So, basically, I need to remove from dataset the items that have the key that it’s not included in fruits (in field key) and then I need to add the field labelToShow.

I dont’ know ho to do that.

I started removing items from dataset doing so:

dataset.removeWhere((k, v) => k != 'pear' && k != 'ananas');

but I don’t like, I would like to loop through fruits.

Can someone please help me?

Thanks a lot

>Solution :

I wouldn’t remove anything from dataset. Instead I’d build a new map from scratch, with just the data you want.

How about:

  Map<String, Map<String, List<String>>> result = {
    for (var fruit in fruits)
      fruit["key"]: {
        "values": dataset[fruit["key"]],
        "labelToShow": fruit["labelToShow"]
      }
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading