JaskeyLam
JaskeyLam

Reputation: 15755

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

Upvotes: 5

Views: 102

Answers (4)

user2575725
user2575725

Reputation:

You may try custom 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

Upvotes: 0

Scimonster
Scimonster

Reputation: 33399

If you feel like using underscore.js, you could try using _.findWhere():

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

Upvotes: 1

Zee
Zee

Reputation: 8488

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

Upvotes: 1

Dibran
Dibran

Reputation: 1545

You could use the filter method of the array.

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
}

Upvotes: 0

Related Questions