Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array of objects includes an object

I am trying to check if an array of objects includes a object. I want it to return true when there is a object in the array that has the same values and the object id should not matter. This is how i thought it would work:

let arr = [{r:0, g:1}];
let obj = {r:0, g:1}

console.log(arr.includes(obj));

But it returns false and I need it to return true. Do I have to convert every object in the array to a string with JSON.stringify() and the object I am searching for like this:

let arr = [JSON.stringify({r: 0, g: 1})]
let obj = {r: 0, g: 1}

console.log(arr.includes(JSON.stringify(obj)));

Is there another easier and more efficient way to do it with more objects?

like image 918
Sackidude Avatar asked Feb 23 '20 14:02

Sackidude


1 Answers

You get false because objects are compared by a reference to the object, while you got there 2 separate object instances.

Wile JSON.stringify might work, keep in mind that the order of properties is not guaranteed and it may fail if the order is not the same, because you get a different string.

you can check for an id property or compare several properties to match against, if you must you can compare all properties with a loop.

If you have an access to the object's reference, you can use a Map or a Set which allows you to store and check references

const obj = {r:0, g:1};
const obj2 = {r:0, g:1};
const mySet = new Set();
// given the fact that you do have access to the object ref
mySet.add(obj);

const isObjInList = mySet.has(obj);
const isObj2InList = mySet.has(obj2);

console.log('is obj in list - ', isObjInList);
console.log('is obj2 in list - ', isObj2InList);
like image 149
Sagiv b.g Avatar answered Sep 19 '22 17:09

Sagiv b.g