简体   繁体   English

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

[英]How to get object that not match in another object lodash

I have 2 arrays with objects. 我有2个对象数组。

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

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

I want to get the object is not the same in the array and also get the object that is same in arrays as well. 我想获取数组中的对象不相同,并且也要获取数组中的对象。

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

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

Using lodash library is it possible? 使用lodash库可以吗?

You can use intersectionBy and xorBy as follows: 您可以按以下方式使用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> 

You can use _.partition() to get two arrays according to a certain criteria: 您可以根据特定条件使用_.partition()获得两个数组:

 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); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM