简体   繁体   中英

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

We have 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'}]

I want to check if at least one item from arr2 is included inside of arr1 (if yes return bool value). So far i tried arr2.some(item => arr1.includes(item)) but this doesn't seem to work.

you can use this code arr2.some(item => arr1.find(e=>JSON.stringify(e) === JSON.stringify(item))

Array.prototype.includes checks if it is equal so it is useful for primitive values. To check if it deep equal (for arrays and objects) you can use find method. So correct solution would be:

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

Array includes() matches the object using reference equality, it does not deep compare item object's properties. So, you also need an object matcher.

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

and you will have to write an implementation of matchObj(obj1, obj2) .

You can also use lodash's isEqual() or intersecttionWith() method:

 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>

If your array of object is small, not too big. You can use JSON.stringify too check.

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))));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM