user13946744
user13946744

Reputation:

How to copy some elements from one Map into a new Map in Dart/Flutter?

How to copy some elements from one Map into a new Map in Dart/Flutter?

Old_Map = {
  'A' : {Big : 'A', Small : 'a' },
  'B' : {Big : 'B', Small : 'b' },
  'C' : {Big : 'C', Small : 'c' },
  'D' : {Big : 'D', Small : 'd' },
}

Old_Map => New_Map

I only want

'B' : {Big : 'B', Small : 'b' },
'C' : {Big : 'C', Small : 'c' },

Upvotes: 1

Views: 1219

Answers (2)

final List<String> desiredKeys = ['B','C'];
final newMap = Map.from(oldMap);
newMap.removeWhere((String key, dynamic value) => !desiredKeys.contains(key));

First make a List containing your desired keys. Then by using removeWhere function remove those.

Upvotes: 0

hewa jalal
hewa jalal

Reputation: 963

you can do it like this

 final oldMap = {
    'A': {'Big': 'A', 'Small': 'a'},
    'B': {'Big': 'B', 'Small': 'b'},
    'C': {'Big': 'C', 'Small': 'c'},
    'D': {'Big': 'D', 'Small': 'd'},
  };

  final newMap =
      Map.fromIterable(oldMap.keys.where((k) => k == 'B' || k =='C'), 
      key: (k) => k, value: (v) => oldMap[v]);

as keys returns an Iterable<String> of your map keys, then you can check which key you want by using where method, then you can fill your values based on old map values.

Upvotes: 2

Related Questions