第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

檢查一個數(shù)組中的對象是否包含在另一個對象數(shù)組中

檢查一個數(shù)組中的對象是否包含在另一個對象數(shù)組中

湖上湖 2022-07-08 15:52:53
我們有 2 個數(shù)組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條經(jīng)驗 獲得超7個贊

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



查看完整回答
反對 回復(fù) 2022-07-08
?
Smart貓小萌

TA貢獻1911條經(jīng)驗 獲得超7個贊

數(shù)組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>


查看完整回答
反對 回復(fù) 2022-07-08
?
阿晨1998

TA貢獻2037條經(jīng)驗 獲得超6個贊

如果您的對象數(shù)組很小,也不會太大。您也可以使用 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))));


查看完整回答
反對 回復(fù) 2022-07-08
?
守候你守候我

TA貢獻1802條經(jīng)驗 獲得超10個贊

Array.prototype.includes 檢查它是否相等,因此它對原始值很有用。要檢查它是否深度相等(對于數(shù)組和對象),您可以使用 find 方法。所以正確的解決方案是:

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


查看完整回答
反對 回復(fù) 2022-07-08
  • 4 回答
  • 0 關(guān)注
  • 473 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號