let a = { first: "Tybalt", last: "Capulet" }
let b = {last: "Capulet" }
如何检查“ a”是否包含“ b”?
答案 0 :(得分:1)
我认为可以通过两种方式获得自己想要的东西
1st->就像Jack Bashford所做的一样
2nd->使用rest运算符创建一个新对象并将其与自身进行比较
let a = { first: "Tybalt", last: "Capulet" }
let b = {last: "Capulet" }
let combinedObj = {...a, ...b}
如果a
中包含b
,则combinedObj
将等于a
。然后,您可以使用任何对象比较模块来检查combinedObj
和a
是否相等。
答案 1 :(得分:1)
尝试一下:
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 ) ;
答案 2 :(得分:0)
遍历较小对象中的每个属性,然后如果不匹配,则返回false
。否则,返回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;
}
演示:
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));
答案 3 :(得分:0)
这应该有效。
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');
答案 4 :(得分:0)
您可以遍历b
对象的每个键,并检查其值是否等于a
对象中该键的值。
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))