为了账号安全,请及时绑定邮箱和手机立即绑定

检查一个数组中的对象是否包含在另一个对象数组中

检查一个数组中的对象是否包含在另一个对象数组中

湖上湖 2022-07-08 15:52:53
我们有 2 个数组const arr1 = [{color: 'red', shape: 'square'}, {color: 'blue', shape: 'circle'}, {color: 'green', shape: 'square}] const arr2 = [{color: 'red', shape: 'circle'}, {color: 'blue', shape: 'circle'}]我想检查 arr2 中的至少一项是否包含在 arr1 中(如果是,则返回 bool 值)。到目前为止,我尝试过arr2.some(item => arr1.includes(item)),但这似乎不起作用。
查看完整描述

4 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

您可以使用此代码 arr2.some(item => arr1.find(e=>JSON.stringify(e) === JSON.stringify(item))



查看完整回答
反对 回复 2022-07-08
?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

数组includes()使用引用相等来匹配对象,它不会深入比较项目对象的属性。因此,您还需要一个对象匹配器。


const overlap = arr1.some(i1 => arr2.some(i2 => matchObj(i1,i2)));

你将不得不编写一个matchObj(obj1, obj2).


您还可以使用 lodash 的isEqual()orintersecttionWith()方法:


const arr1 = [{color: 'red', shape: 'square'}, {color: 'blue', shape: 'circle'}, {color: 'green', shape: 'square'}];

const arr2 = [{color: 'red', shape: 'circle'}, {color: 'blue', shape: 'circle'}];


// check for overlap

const hasCommon = _.some(arr1, i1 => _.some(arr2, i2 => _.isEqual(i1, i2)));

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


// get common items

const commonItems = _.intersectionWith(arr1, arr2, _.isEqual);

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

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>


查看完整回答
反对 回复 2022-07-08
?
阿晨1998

TA贡献2037条经验 获得超6个赞

如果您的对象数组很小,也不会太大。您也可以使用 JSON.stringify 检查。


const arr1_str = JSON.stringify(arr1);

arr2.some(item2 => arr1_str.includes(JSON.stringify(item2)));

const arr1 = [{color: 'red', shape: 'square'}, {color: 'blue', shape: 'circle'}, {color: 'green', shape: 'square'}];

const arr2 = [{color: 'red', shape: 'circle'}, {color: 'blue', shape: 'circle'}];


const arr1_str = JSON.stringify(arr1);

console.log(arr2.some(item2 => arr1_str.includes(JSON.stringify(item2))));


查看完整回答
反对 回复 2022-07-08
?
守候你守候我

TA贡献1802条经验 获得超10个赞

Array.prototype.includes 检查它是否相等,因此它对原始值很有用。要检查它是否深度相等(对于数组和对象),您可以使用 find 方法。所以正确的解决方案是:

arr2.some(item => arr1.find(e=>e.color==item.color&&e.shape==item.shape))


查看完整回答
反对 回复 2022-07-08
  • 4 回答
  • 0 关注
  • 507 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号