Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 881
JaskeyLam Avatar asked Oct 31 '22 03:10

JaskeyLam


1 Answers

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);
like image 194
Zee Avatar answered Nov 12 '22 15:11

Zee