Check if array of objects includes an object

Sackidude :

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?

artanik :

JSON.stringify doesn't work as expected if you change the order of properties in one of the objects.

You can use .some in combination with isEqual from lodash (or other alternatives). Or you can write it by yourself, but be careful, there are too many edge cases, that's why I recommend using an existing approach. There is no need to reinvent the wheel.

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

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

let arr2 = [{r:0, g:1}];
let obj2 = {g:1, r:0};

console.log(arr2.some(item => _.isEqual(item, obj2)));
console.log(_.some(arr2, item => _.isEqual(item, obj2))); // more canonical way
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=6997&siteId=1