I need to check if an object is logically in an array, when two object are logically equals(Just like the equals
in Java), it will be treated as "in" the array
While I use $.inArray
of jQuery
to test below code, it retuans -1,indicating that the copied one is not treated as "in" the array.
var a =[{value: "G27", title: "G27"}];
$.inArray({value: "G27", title: "G27"},a); //returns -1
Above is just an example ,Is there an easy way for generic cases to achieve that
A workaround would be to check for 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With