Suppose i have an array of objects
var arr= [{name:'John', lastName:'Smith', age:25}, {name:'Steve', lastName:'Johnson', age:56}];
var obj1 ={name:'John', lastName:'Smith'};
How to check if an object exists within another object using JS ?
Will nested looping do the trick ? The first loops through the objects inside the array, the second loops through key/value pairs inside the object and compares them to the obj1 key/value pairs ? Is there a better way to do this ? or should i use a 3 loops?
the function should return the obj el in the arr that contains obj1. For example: arr[0] should be returned since it contains obj1
function objInArr(srcArr, obj) {
var arr = [];
//var srcLength = 0;
//var sourceSize = Object.keys(source).length; // The length of the source obj
srcArr.forEach(function(el) {
el.forEach(function(objEl){
obj.forEach(function(sourceEl){
if( sourceEl === objEl) { arr.push(sourceEl); }
});
});
});
return arr;
}