james Oduro james Oduro - 7 days ago 7
Javascript Question

Find an entire object in array of objects

How do I find Array2 in Array1 . I have been using $.inArray() method or indexOf() but it return false yet the statement is true.

var array1 = [{
h: 1480508328,
rid: 16,
sid: 2
}, {
h: 87542,
rid: 18,
sid: 9
}
];
var array2 = {
h: 1480508328,
rid: 16,
sid: 2
};
//test if array2 exist in array1
if ($.inArray(array2, array1) > 0) {
console.log('Object is in array');
} else {
console.log('Object is not in array');
}


Please help. Thank you

Answer

You can stringify it and check for equality

var array1 = [{
    h: 1480508328,
    rid: 16,
    sid: 2
  }, {
    h: 87542,
    rid: 18,
    sid: 9
  }
];
var array2 = {
  h: 1480508328,
  rid: 16,
  sid: 2
};

var dat1 = JSON.stringify(array2);
array1.forEach(function(item){
    if(JSON.stringify(item) === dat1){
        console.log(dat1)
    } else {
        console.log('Not match')
    }
});

JSFIDDLE