Skip to content

Instantly share code, notes, and snippets.

@aya-eiya
Last active July 27, 2020 03:41
Show Gist options
  • Save aya-eiya/6ec24741667fb65aac121cb7f130cddd to your computer and use it in GitHub Desktop.
Save aya-eiya/6ec24741667fb65aac121cb7f130cddd to your computer and use it in GitHub Desktop.
Mapをマージしたいという質問への回答
void main() {
// 値を直接弄ってはいけない
// const か Map.unmodifiable で保護する
const firstMap = [
{"id": 333, "name": "山田 太郎", "gender": "F", "birth_date": "19880205"},
{"id": 111, "name": "山田 次郎", "gender": "F", "birth_date": "19880205"},
{"id": 121, "name": "山田 花子", "gender": "F", "birth_date": "19880205"}
];
const secondMap = [
{
"id": 1111111,
"member_id": 222,
"score": 98,
"created_at": "2019-01-09T14:00:00+09:00",
"updated_at": "2019-01-09T14:00:00+09:00"
},
{
"id": 1111112,
"member_id": 333,
"score": 50,
"created_at": "2019-01-09T14:00:00+09:00",
"updated_at": "2019-01-09T14:00:00+09:00"
}
];
// このキーはマージしないでいいよね?
const excludeKeys = ['id', 'member_id'];
// Listがid被りをしていないことを祈ってMapに変換している
// マージするため、Map<int,mutable Map>
final _firstMap = toMap('id', firstMap);
final _secondMap = toMap('member_id', secondMap);
// 2つのMapをexcludeKeysを除いてマージする
// 結果は再びMapを不変として、List<const Map>
final marged = _firstMap
.map((int key, Map<String, dynamic> d) => MapEntry(
key,
Map.unmodifiable(_secondMap.containsKey(key)
? (d..addEntries(_secondMap[key]
.entries
.where((e) => !excludeKeys.contains(e.key))))
: d)))
.values
.toList(growable: false);
print(marged);
}
// List<const Map>をMap<int,mutable Map>に変換
Map<int, Map<String, dynamic>> toMap(
String key, List<Map<String, dynamic>> list) =>
Map.fromEntries(list.map((d) => MapEntry(d[key], Map.from(d))));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment