javascript - 合并两个数组时创建唯一数组
问题描述
我想合并两个对象数组。这两个数组中的一个键将是相同的。
这是示例数据:
var a = ['Europe', 'Africa', 'Antarctica'];
var b = [
{id: 11, warehouse_name: 'Europe', input_qty: 200, total_amt: 4000},
{id: 12, warehouse_name: 'Africa', input_qty: 150, total_amt: 3500},
{id: 13, warehouse_name: 'Africa', input_qty: 20, total_amt: 500},
{id: 14, warehouse_name: 'Antarctica', input_qty: 50, total_amt: 1500}
];
我的预期输出应该是:
var c = [
{warehouse_name: 'Europe', pack: [{id: 11, warehouse_name: 'Europe', input_qty: 200, total_amt: 4000}]},
{warehouse_name: 'Africa', pack: [{id: 12, warehouse_name: 'Africa', input_qty: 150, total_amt: 3500}, {id: 13, warehouse_name: 'Africa', input_qty: 20, total_amt: 500}]},
{warehouse: 'Antarctica', pack: [{id: 14, warehouse_name: 'Antarctica', input_qty: 50, total_amt: 1500}]}
];
我如何使用 lodash 或不使用 lodash 在 javascript 中实现这一点。任何解决方案表示赞赏。
解决方案
您可以使用数组Array.prototype.map()
方法来做到这一点。使用 map遍历数组并使用方法按数组值a
过滤 b 数组。a
Array.prototype.filter
const a = ['Europe', 'Africa', 'Antarctica'];
const b = [
{ id: 11, warehouse_name: 'Europe', input_qty: 200, total_amt: 4000 },
{ id: 12, warehouse_name: 'Africa', input_qty: 150, total_amt: 3500 },
{ id: 13, warehouse_name: 'Africa', input_qty: 20, total_amt: 500 },
{ id: 14, warehouse_name: 'Antarctica', input_qty: 50, total_amt: 1500 },
];
const ret = a.map((x) => ({
warehouse_name: x,
pack: b.filter((y) => y.warehouse_name === x),
}));
console.log(ret);
推荐阅读
- python - 拆分网址并获取新网址
- firebase - 如何从 Dart 中的 Cloud Firestore 获取随机文档(对于 Flutter)?
- symfony - Symfony Messenger - 检查队列是否为空
- javascript - 如何在单击按钮时从多个 v-text-fields 中清除数据?
- python-3.x - 如何在 Python 中查找给定时间范围内的所有记录(表单列表)?
- android - 向特定国家/地区提供应用更新
- c# - 如何获取以 ^ 开头和结尾的单词
- flutter - 使用单独的背景颜色自定义颤振导航栏/标签栏
- php - 成功更新后`缺少必需参数:id`
- sql - 无法访问 azure sql 数据库中的临时表