Audite Marlow Audite Marlow - 6 months ago 16
Javascript Question

Check if array contains object without reference

I have the following function:

function containsObject(object, array) {
for (var i = 0; i < array.length; i++) {
if (array[i] === object) {
return i;
}
}

return false;
}


The following array:

var array = [
{
name: 'test1',
age: 12
},
{
name: 'test2',
age: 14
}
];


And I need to check if the following object is in the array:

var object = {
name: 'test1',
age: 12
};


But when I use the function to check if the array contains the object:

console.log(containsObject(object, array));


It will return
false
, since the references of the objects aren't the same. So technically speaking, the objects aren't the same.

How do I go on about this without sharing references?

Answer

I ended up going with thatOneGuy's solution, altering it so it can search both arrays and objects:

function containsObject(needle, haystack) {
    for (var i in haystack) {
        var count    = 0,
            matching = true;

        for (var key in needle) {
            if (haystack[i][key] === needle[key]) {
                matching = true;

                if (count == Object.keys(haystack[i]).length - 1 && matching) {
                    return i;
                } else {
                    count++;
                }
            } else {
                matching = false;
            }
        }
    }

    return false;
}