【问题标题】:Create unique array when merging two array合并两个数组时创建唯一数组
【发布时间】:2021-02-24 10:35:06
【问题描述】:

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

这里是示例数据:

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

如何在 javascript 中使用 lodash 或不使用 lodash 来实现这一点。任何解决方案都值得赞赏。

【问题讨论】:

  • 具有不变原始对象的唯一数组?

标签: javascript node.js arrays lodash


【解决方案1】:

使用_.groupBy() 从数组b 中通过warehouse_name 创建一个对象(byWarehouse)。现在映射数组a,并从byWarehouse 中获取项目以创建对象:

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 byWarehouse = _.groupBy(b, 'warehouse_name')

const result = a.map(warehouse_name => ({ warehouse_name, pack: byWarehouse[warehouse_name] }))

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

【讨论】:

    【解决方案2】:

    您可以使用数组Array.prototype.map() 方法来做到这一点。使用map遍历a数组,使用Array.prototype.filter方法通过a数组值过滤b数组。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 2017-11-14
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      相关资源
      最近更新 更多