2017-08-04 122 views
0

我有2個對象數組。如何獲得不匹配另一個對象的對象lodash

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

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

我想要得到的數組中的對象是不一樣的,並且也得到在數組中同樣的對象。

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

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

使用lodash庫有可能嗎?

+1

你有試過什麼嗎? –

+0

自己嘗試一下,然後回到問題。提示:https://lodash.com/docs/4.17.4#find –

回答

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>

0

您可以使用_.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>