Farkhod
Farkhod

Reputation: 109

How to merge two array of objects based on a key in Dart/Flutter

I have 2 arrays of maps where one of them has product ids and quantities; and the other one has product ids, product names and price:

List<Map<String, dynamic>> arr1 = [
    { id: "1", name:"First Item", price: 10 },
    { id: "2", name: "Second Item", price: 12 }
];

List<Map<String, dynamic>> arr2 = [
    { id: "1", quantity: 1 },
    { id: "2", quantity: 3 },
    { id: "3", quantity: 2 }
];

Now I need to get total price of products by combining two arrays by obtaining sum of price * quantites.

I need an array similar to this:

List<Map<String, dynamic>> arr3 =[
   { id: "1", name:"First Item", price: 10, quantity: 1 },
   { id: "2", name: "Second Item", price: 12, quantity: 3 }
];

How can I merge them into one array based on their ids?

Upvotes: 1

Views: 4171

Answers (1)

Jonas Franz
Jonas Franz

Reputation: 595

You can merge the array by mapping the first array to the second one.

  final arr3 = arr1.map((product) {
    final quantity = arr2
        .where((quantities) => quantities["id"] == product["id"])
        .map((quantities) => quantities["quantity"] as int)
        .first;
    return product..["quantity"] = quantity;
  });

Full example: https://dartpad.dev/67148d132cb930bc6f1cee6a8a4fcff1

Upvotes: 5

Related Questions