1

In my Ajax success function data, I am getting a list of objects. I have one more array list with objects which are of same type. How to write a condition to check if that object contains in my list?

//In my Ajax Success function
$.each(data, function(index, item) {
//This is my another array list
var target = [];
target = self.target();                    
//Need to check the condition whether the above "item" is in my above array list

I am doing something like this, its not working

if (target.indexOf(item) !== -1) {
    //item is not present in the above target array list 
    console.log(item);
} else {
    console.log(item.FullName);
}
Cherry
  • 675
  • 3
  • 10
  • 28
  • `indexOf` will only work if the Object in the Array is the same as your "item" (one Object, referenced in multiple places). If these Objects were created separately, it won't ([JS Fiddle demo](https://jsfiddle.net/5ner6ta6/)). In your case, I would use [`Array.some()`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/some) with [this method to compare Objects](http://stackoverflow.com/a/1144249/1913729). [JS Fiddle Demo](https://jsfiddle.net/2zhw5Lvp/) – blex May 27 '16 at 14:00

1 Answers1

3

From How to determine if object is in array

function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
    if (list[i].YourId === obj.Id) {
        return true;
    }
}

return false;
}
Community
  • 1
  • 1
Cherry
  • 675
  • 3
  • 10
  • 28