imesh madushanka
imesh madushanka

Reputation: 3

needs to convert Lists of map data into One map

My question is about dart....

the result I got [{'sam': 8}, {'john': 822}]

I need to convert it into like below {'sam': 8, 'john': 822}

pls help me. thanks for reading

Upvotes: 0

Views: 78

Answers (2)

julemand101
julemand101

Reputation: 31199

Something like this?

void main() {
  final listOfMaps = [
    {'sam': 8},
    {'john': 822},
  ];
  final map = {for (final map in listOfMaps) ...map};
  print(map); // {sam: 8, john: 822}
}

Update after example of data has been uploaded

I have made the following example which parses the input you have posted as returns the expected data:

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"
  }
];

Upvotes: 2

developerjamiu
developerjamiu

Reputation: 654

This is a longer approach and probably more understandable.

// 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;
}

Upvotes: 0

Related Questions