let a = { first: "Tybalt", last: "Capulet" }
let b = {last: "Capulet" }
How do I check if 'a' contains 'b'?
let a = { first: "Tybalt", last: "Capulet" }
let b = {last: "Capulet" }
How do I check if 'a' contains 'b'?
I think there are two ways to obtain what you desire
1st-> like Jack Bashford has done with his answer
2nd -> use rest operators to make a new object and compare object with itself
let a = { first: "Tybalt", last: "Capulet" }
let b = {last: "Capulet" }
let combinedObj = {...a, ...b}
if a
contains b
in it, the combinedObj
will be equal to a
. Then you can use any object comparison module to check if combinedObj
and a
are equal or not.
Try This :
let a = { first: "Tybalt", last: "Capulet", age: 20 }
let b = { last: "Capulet", first:"Tybalt" }
var result = false ;
function getLength(obj) {
var len = 0 ;
for( key in obj )
len++ ;
return len ;
}
if ( getLength(a) >= getLength(b) ) {
for ( key in b ) {
if (b[key] !== a[key] ) {
result = false ;
break ;
}
result = true ;
}
}
console.log( result ) ;
Iterate through each property in the smaller object, then if there are any that don't match, return false
. Otherwise, return true
:
let a = { first: "Tybalt", last: "Capulet" };
let b = {last: "Capulet" };
function bigObjContainsSmallObj(big, small) {
for (var prop in small) {
if (small[prop] != big[prop]) {
return false;
}
}
return true;
}
Demonstration:
let a = {
first: "Tybalt",
last: "Capulet"
};
let b = {
last: "Capulet"
};
let c = {
first: "Romeo"
}
function bigObjContainsSmallObj(big, small) {
for (var prop in small) {
if (small[prop] != big[prop]) {
return false;
}
}
return true;
}
console.log(bigObjContainsSmallObj(a, b));
console.log(bigObjContainsSmallObj(a, c));
This should work.
function checkObj(obj, obj2, property){
if( obj.hasOwnProperty( property ) ) {
console.log('Yes. It has the '+ property);
if(obj[property] === obj2[property]){
console.log('And the values are both '+ obj2[property]);
}
}
}
checkObj(a, b, 'last');
You can iterate through each keys of b
object and check if its value is equal to value of that key in a
object.
let a = { first: "Tybalt", last: "Capulet" },
b = { last: "Capulet" },
c = { here: 'property'},
isObjectPresent = (a, b) => {
return Object.keys(b).every(k => k in a && a[k] === b[k]);
}
console.log(isObjectPresent(a,b));
console.log(isObjectPresent(a,c))