Ven Shine
Ven Shine

Reputation: 9326

How to flatten a List<Map> in Dart?

How can I flatten a List in Dart? just like flatMap. For example:

var a = [{"a":1, "b":1}, {"b":2, "c":2}, {"d":4, "c":3}];
var b = {"a":1, "b":2, "c":3, "d":4};

How can I turn a to b into a single List?

Upvotes: 0

Views: 3058

Answers (2)

jamesdlin
jamesdlin

Reputation: 90015

You can use Dart's collection-for construct and spread operator to succinctly build a Map from the elements of your List:

var a = [
  {"a": 1, "b": 1},
  {"b": 2, "c": 2},
  {"d": 4, "c": 3},
];

var b = <String, int>{for (var map in a) ...map};

Upvotes: 6

Bach
Bach

Reputation: 3326

How can I turn a to b into a single List?

It's a bit confusing with your question. Right now, I'm assuming you want to turn a to b. In this case, you can do this:

var new_a = a.expand((map) => map.entries).toList();
print(new_a); 
// Output: [MapEntry(a: 1), MapEntry(b: 1), MapEntry(b: 2), MapEntry(c: 2), MapEntry(d: 4), MapEntry(c: 3)]

var b = Map.fromIterable(new_a, key: (v) => v.key, value: (v) => v.value);
print(b); 
// Output: {a: 1, b: 2, c: 3, d: 4}

Upvotes: 1

Related Questions