Lodash - 在条件下合并两个数组的对象 [英] Lodash - Merge objects of two arrays on condition

查看:175
本文介绍了Lodash - 在条件下合并两个数组的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象数组。

arr1 = [
  {
    myName: 'Adam',
    mySkill: 'CSS',
  },
  {
    myName: 'Mutalib',
    mySkill: 'JavaScript',
  },
];

arr2 = [
  {
    myName: 'Adam',
    myWeight: '112',
  },
  {
    myName: 'Habib',
    myWeight: '221',
  },
];

我想要的结果是一个数组,其中包含具有匹配属性myName的第一个数组的对象在第二个数组中,具有相应的第二个数组对象的附加属性。

The result I want is an array that contains objects of first array that have a matching property "myName" in second array, with the additional properties of the corresponding second array object.

result = [
  {
    myName = 'Adam'
    mySkill = 'CSS'
    myWeight = '112'
  }
];


推荐答案

以下解决方案 groups 连接数组( arr1 arr2 )通过 myName ,使用拒绝,最后使用地图合并生成的数组。

The solution below groups the concatenated array (arr1 and arr2) by myName, removes all groups that only contains one item using reject, and lastly use map to merge the resulting array.

var result = _(arr1)
  .concat(arr2)
  .groupBy('myName')
  .reject({ length: 1 })
  .map(_.spread(_.merge))
  .value();

var arr1 = [
  {
    myName: 'Adam',
    mySkill: 'CSS',
  },
  {
    myName: 'Mutalib',
    mySkill: 'JavaScript',
  }
];

var arr2 = [
  {
    myName: 'Adam',
    myWeight: '112',
  },
  {
    myName: 'Habib',
    myWeight: '221',
  }
];

var result = _(arr1)
  .concat(arr2)
  .groupBy('myName')
  .reject({ length: 1 })
  .map(_.spread(_.merge))
  .value();

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

另一种解决方案是使用 intersectionWith to得到两个数组之间的交集,并同时分配缺失值。请注意使用 cloneDeep 来提升不变性。

An alternative solution is to use intersectionWith to get the intersection between two arrays and assign the missing values at the same time. Note the use of cloneDeep to promote immutability.

var result = _.intersectionWith(_.cloneDeep(arr1), arr2, function(x, y) {
  return x.myName === y.myName && _.assign(x, y);
});

var arr1 = [
  {
    myName: 'Adam',
    mySkill: 'CSS',
  },
  {
    myName: 'Mutalib',
    mySkill: 'JavaScript',
  }
];

var arr2 = [
  {
    myName: 'Adam',
    myWeight: '112',
  },
  {
    myName: 'Habib',
    myWeight: '221',
  }
];

var result = _.intersectionWith(_.cloneDeep(arr1), arr2, function(x, y) {
  return x.myName === y.myName && _.assign(x, y);
});
  
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

这篇关于Lodash - 在条件下合并两个数组的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆