2017-08-04 4 views
0

オブジェクトが2つあります。他のオブジェクトで一致しないオブジェクトを取得する方法

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

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

私はオブジェクトを取得したいが、アレイに同じではなく、また、同様の配列と同じであるオブジェクトを取得します。

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

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

ロダッシュライブラリの使用は可能ですか?次のように

+1

試しましたか? –

+0

あなた自身で何かを試してから、質問に戻ってください。ヒント:https://lodash.com/docs/4.17.4#find –

答えて

0

あなたはxorByintersectionBy使用してすることができます

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>

関連する問題