Home > other >  Flutter:How to merge two objects and sum the values of the same key?
Flutter:How to merge two objects and sum the values of the same key?

Time:10-17

map1 = { "a": 10, "b": 6 }, map2 = { "a": 10, "b": 6, "c": 7, "d": 8 };

Flutter:How to merge two objects and sum the values of the same key?

CodePudding user response:

Do forEach on the longest map and check if the small map contains the key if it does then update the value with the sum or add the new.

  map2.forEach((key, value) {
    if (map1.containsKey(key)) {
      map1[key] = value   map1[key]!;
    } else {
      map1[key] = map2[key]!;
    }
  });

map1 will be the final result.

CodePudding user response:

So, if you want to combine/merge the two maps use this code this answer:

final firstMap = {"1":"2"};
final secondMap = {"2":"3"};

final thirdMap = { // here simple adding element to map
...firstMap,
...secondMap,
};

but if you want to make sum and merge use this :

map2.forEach((k, v) {
if (map1.containsKey(k)) { // check if the map has more then 2 values as the 1st one
  map1[k] = v   map1[k]!; // if yes so make the some
} else {
  map1[k] = map2[k]!; // if no then add the values to map
}
});

as MEET Prajapati asnwer.

  • Related