首页 > 解决方案 > 合并两个数组时创建唯一数组

问题描述

我想合并两个对象数组。这两个数组中的一个键将是相同的。

这是示例数据:

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 中实现这一点。任何解决方案表示赞赏。

标签: javascriptnode.jsarrayslodash

解决方案


您可以使用数组Array.prototype.map()方法来做到这一点。使用 map遍历数组并使用方法按数组值a过滤 b 数组。aArray.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);


推荐阅读