How to check if an object is logically in an array, JavaScript

I need to check if an object is logically in an array, when two objects are logically equal (same as equals in Java), it will be considered as "in" the array

While I am using $.inArray of jQuery to check the code below, it retuns -1, indicating that the copied is not being processed as "in" the array.

 var a =[{value: "G27", title: "G27"}]; $.inArray({value: "G27", title: "G27"},a); //returns -1 

The above is just an example. Is there an easy way for general cases to achieve this

+5
source share
4 answers

A workaround would be to check each key-value pair in a for loop:

 function exist(arr, obj){ var len = Object.keys(obj).length; var count = 0; for(var i=0;i<arr.length;i++){ count=0; for(var key in obj){ if(obj[key] == arr[i][key]){ count++; } } if(count == len && count == Object.keys(arr[i]).length){ console.log("Exists!!"); return; } } console.log("Don't exist!!"); } var arr =[{value: "G27", title: "G27"}]; var b = {value: "G27", title: "G27"}; //Call exist(arr, b); 
+1
source

If you like to use underscore.js, you can try using _.findWhere() :

 var a = [{value: "G27", title: "G27"}]; snippet.log(_.findWhere(a, {value: "G27", title: "G27"}) !== undefined); // returns true 
 <script src="http://tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script> <script src="http://underscorejs.org/underscore-min.js"></script> 
+1
source

You can use the array filtering method.

 var arr = [{value: "G27", title: "G27"}]; // Don't call filter on arr because this will mutate arr itself. Instead of creating a new array. var filteredArr = Array.prototype.filter.call(arr, function(item) { return item.value == "G27" && iem.title == "G27"; }); if(filteredArr.length > 0) { // Item exists } 
0
source

You can try an individual search:

 var indexOf = function(array, obj) { var i = array.length; var o; while (o = array[--i]) //note, its assignment if (obj.value === o.value && obj.title === o.title) break; return i; }; var arr = [{ value: "G27", title: "G27" }, { value: "G28", title: "G28" }, { value: "G29", title: "G29" }]; console.log(indexOf(arr, { title: "G28", value: "G28" })); //<-- 1 console.log(indexOf(arr, { title: "G30", value: "G30" })); //<-- -1 
0
source

All Articles