我的问题是关于飞镖。。。。
我得到的结果[{‘sam’:8},{‘john’:822}]
我需要将其转换为如下{"am":8,"john":822}
请帮帮我。感谢阅读
类似的东西?
void main() {
final listOfMaps = [
{'sam': 8},
{'john': 822},
];
final map = {for (final map in listOfMaps) ...map};
print(map); // {sam: 8, john: 822}
}
上传数据示例后更新
我做了下面的例子,解析你发布的输入,返回预期的数据:
void main() {
final map = {
for (final map in someListOfMaps)
for (final voted in map['voted']! as List<Map<String, String>>)
for (final vote in voted.entries) vote.key: int.parse(vote.value)
};
print(map);
// {60e6956078fb6f42da: 1, 60e6956020d8bf42db: 5, 120d8bf42dffsww66: 1, jd58466daa4dw2: 20, gg4c577x6ad8ds6a: 6}
}
const someListOfMaps = [
{
"voted": [
{"60e6956078fb6f42da": "1"},
{"60e6956020d8bf42db": "5"}
],
"_id": "60e698fe78fb6120d8bf42dd",
"name": "donald"
},
{
"voted": [
{"120d8bf42dffsww66": "1"}
],
"_id": "60e698fe78fb6120d8bf42de",
"name": "barrack"
},
{
"voted": [
{"jd58466daa4dw2": "20"}
],
"_id": "60e698fe78fb6120d8bf42df",
"name": "malan"
},
{
"voted": [
{"gg4c577x6ad8ds6a": "6"}
],
"_id": "60e698fe78fb6120d8bf42e0",
"name": "kuma"
}
];
这是一种更长的方法,可能更容易理解。
// the result I got [{'sam': 8}, {'john': 822}]
// I need to convert it into like below {'sam': 8, 'john': 822}
void main() {
final mapList = [{'sam': 8}, {'john': 822}];
print(mapListToJustMap(mapList)); // output: {sam: 8, john: 822}
// The <int> is not required
print(genericMapListToJustMap<int>(mapList)); // output: {sam: 8, john: 822}
}
Map<String, int> mapListToJustMap(List<Map<String, int>> mapList) {
// Create a new empty map object
final newMap = <String, int>{};
// Iterate through the mapList input
for (final singleMap in mapList) {
// add the current iteration to the new map object
newMap.addAll(singleMap);
}
return newMap;
}
// A generic approach
Map<String, T> genericMapListToJustMap<T>(List<Map<String, T>> mapList) {
// Create a new empty map object
final newMap = <String, T>{};
// Iterate through the mapList input
for (final singleMap in mapList) {
// add the current iteration to the new map object
newMap.addAll(singleMap);
}
return newMap;
}