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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

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

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

湖上湖 2022-07-08 15:52:53
我們有 2 個(gè)數(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 中的至少一項(xiàng)是否包含在 arr1 中(如果是,則返回 bool 值)。到目前為止,我嘗試過(guò)arr2.some(item => arr1.includes(item)),但這似乎不起作用。
查看完整描述

4 回答

?
吃雞游戲

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊

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



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

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊

數(shù)組includes()使用引用相等來(lái)匹配對(duì)象,它不會(huì)深入比較項(xiàng)目對(duì)象的屬性。因此,您還需要一個(gè)對(duì)象匹配器。


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

你將不得不編寫一個(gè)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>


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

TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊

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


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

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊

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

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


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

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

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