首页 > 解决方案 > 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?

标签: arraysflutterdartmaps

解决方案


您可以通过将第一个数组映射到第二个数组来合并数组。

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

完整示例:https ://dartpad.dev/67148d132cb930bc6f1cee6a8a4fcff1


推荐阅读