Does "includes" work with objects or do I need to use another
function?
Includes works with objects, but it compares objects by reference.
In your case, despite the first element of itemsObject
has the same keys and values of itemToSearch
, they are different objects, hence includes will not work, since, for objects cases, it looks for the same object instance.
In order to make it work, you can use several alternatives, like .find
, .some
, .filter
.
Another solution, which I personally don't recommend but I think that it's worth mentioning, is that you can use .includes
if you first map items to strings instead. In that case, using JSON.stringify, you can check whether the objects are the same. BEWARE: this will work with single key items only. JSON.stringify doesn't preserve key and values order, so it works with single keys objects only (unless keys and values are in the same order in the original stringified object). Moreover, the JSON.stringify way is way heavier and less performant than the others, I just think it's worth mentioning that as an example.
Below some examples with each of them.
var itemsString = ["name1", "name2"];
var itemsObject = [{ name: "name1" }, { name: "name2" }];
var itemToSearch = { name: "name1" };
console.log(itemsObject.some(r => r.name === itemToSearch.name));
console.log(!!itemsObject.find(r => r.name === itemToSearch.name));
// ^--- !! is used to cast to boolean.
console.log(itemsObject.filter(r => r.name === itemToSearch.name).length > 0);
console.log(itemsObject.map(i => JSON.stringify(i)).includes(JSON.stringify(itemToSearch)));
// ^--------------^ ^---------------------------------------^
// |------ this will stringify each object, converting it to a json string. |
// |
// this will check whether the string[] includes any stringified value.--^