簡體   English   中英

檢查一個數組中的 object 是否包含在另一個對象數組中

[英]Check if object from one array is included inside another array of objects

我們有 2 個 arrays

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))但這似乎不起作用。

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

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

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

數組includes()使用引用相等匹配 object,它不深入比較項目對象的屬性。 因此,您還需要一個 object 匹配器。

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

你將不得不編寫matchObj(obj1, obj2)的實現。

您還可以使用 lodash 的isEqual()intersecttionWith()方法:

 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>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM