如何在另一个对象lodash中获取不匹配的对象

时间:2017-08-04 06:41:45

标签: javascript lodash

我有两个带对象的数组。

const a = [
 {
  name: 'John'
 },
 {
  name: 'Adam'
 }
]

const b = [
 {
  name: 'Adam'
 }
]

我想让对象在数组中不一样,并且也得到数组中相同的对象。

const same = [
 {
  name: 'Adam'
 }
]

const not_same = [
 {
  name: 'John'
 }
]

可以使用lodash库吗?

2 个答案:

答案 0 :(得分:0)

您可以按如下方式使用intersectionByxorBy



const a = [{
    name: 'John'
  },
  {
    name: 'Adam'
  }
];

const b = [{
  name: 'Adam'
}];

console.log(_.intersectionBy(a, b, 'name')); // values present in both arrays
console.log(_.xorBy(a, b, 'name')); // values present in only one of the arrays

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

答案 1 :(得分:0)

您可以使用_.partition()根据特定条件获取两个数组:

&#13;
&#13;
const a = [{
    name: 'John'
  },
  {
    name: 'Adam'
  }
];

const b = [{
  name: 'Adam'
}];

const bMap = _.keyBy(b, 'name'); // create a map of names in b
const [same, not_same] = _.partition(a, ({ name }) => name in bMap); // partition according to bMap and destructure into 2 arrays

console.log('same: ', same);

console.log('not_same: ', not_same);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;