Home > Net >  Filter and manipulate a map
Filter and manipulate a map

Time:02-23

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:

  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

CodePudding user response:

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"]
      }
  };
  • Related