我有两个带对象的数组。
const a = [
{
name: 'John'
},
{
name: 'Adam'
}
]
const b = [
{
name: 'Adam'
}
]
我想让对象在数组中不一样,并且也得到数组中相同的对象。
const same = [
{
name: 'Adam'
}
]
const not_same = [
{
name: 'John'
}
]
可以使用lodash库吗?
答案 0 :(得分:0)
您可以按如下方式使用intersectionBy
和xorBy
:
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;
答案 1 :(得分: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);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;