Reputation: 121
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;
}
Upvotes: 1
Views: 4378
Reputation: 43078
// object contains subObject
function partialContains(object, subObject) {
// Create arrays of property names
const objProps = Object.getOwnPropertyNames(object);
const subProps = Object.getOwnPropertyNames(subObject);
if (subProps.length > objProps.length) {
return false;
}
for (const subProp of subProps) {
if (!object.hasOwnProperty(subProp)) {
return false;
}
if (object[subProp] !== subObject[subProp]) {
return false;
}
}
return true;
}
You can now use it like this:
const arr= [{name:'John', lastName:'Smith', age:25}, {name:'Steve', lastName:'Johnson', age:56}];
const obj1 ={name:'John', lastName:'Smith'};
const containing = arr.find((object) => partialContains(object, obj1));
if containing
is undefined, nothing was found, otherwise, the object that contains obj1
is returned.
Upvotes: 0
Reputation: 32145
You can use a combination of Arry#find()
and Array#some()
methods to loop over your array objects and find if an object with the same keys and values exists or not:
var exists = arr.find(function(o){
return Object.keys(o).some(function(k){
return !Object.keys(obj1).indexOf(k)>-1 || o[k]!=obj1[k];
});
});
It will return an object
if it exists, if you want to return a boolean
you can change the .find()
with a .some()
.
Here the statement !Object.keys(obj1).indexOf(k)>-1 || o[k]!=obj1[k]
will quit if an object doesn't have the iterated key
or it's value
its' not the same.
Demo:
var arr= [{name:'John', lastName:'Smith', age:25}, {name:'Steve', lastName:'Johnson', age:56}];
var obj1 ={name:'John', lastName:'Smith'};
var exists = arr.find(function(o){
return Object.keys(o).some(function(k){
return !Object.keys(obj1).indexOf(k)>-1 || o[k]!=obj1[k];
});
});
console.log(exists);
Upvotes: 2