arrays - 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?
解决方案
您可以通过将第一个数组映射到第二个数组来合并数组。
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;
});
推荐阅读
- hybris - 将表单数据从 Spartacus Storefront 发送到 Hybris 后端控制器
- c# - .NET Core 库未读取配置文件
- json - JSON模式验证数组的头部和尾部
- firebase - 如何从 Firebase 获取随机孩子
- sql-server - 如何记录存储过程执行运行时间
- unit-testing - Mockito - Kotlin 测试在尝试捕获 Pageable 参数时抛出空指针异常
- sql - 如何在 postgresql 中使用带有数组列的 GIN 索引?
- javascript - React - 通过链接到浏览器页面时如何更改样式
- reactjs - React 索引保持相同的值 (0)
- javascript - 获取 TypeError:尝试设置 props.children 时 props.children 不是函数