Benjamin
Benjamin

Reputation: 6191

How to get a list of map values from a map inside a list?

Let's say I have a list that goes like this!

List<Map<String, String>> names = [
  {'name': 'John'},
  {'name': 'Adam'},
  {'name': 'Sean'},
  {'name': 'Shirley'},
  {'name': 'Samantha'},
];

How would I be able to retrieve only the list of values inside the map?

I want the output to be this:

List<String> names = [
  'John',
  'Adam',
  'Sean',
  'Shirley',
  'Samantha',
];

Upvotes: 0

Views: 54

Answers (1)

julemand101
julemand101

Reputation: 31309

Something like this:

void main() {
  List<Map<String, String>> names = [
    {'name': 'John'},
    {'name': 'Adam'},
    {'name': 'Sean'},
    {'name': 'Shirley'},
    {'name': 'Samantha'},
  ];

  final onlyNames1 = names.map((map) => map.values.first).toList();
  final onlyNames2 = names.expand((map) => map.values).toList();
  print(onlyNames1); // [John, Adam, Sean, Shirley, Samantha]
  print(onlyNames2); // [John, Adam, Sean, Shirley, Samantha]
}

Upvotes: 1

Related Questions