检查对象是否包含在另一个对象中

时间:2018-12-23 03:23:34

标签: javascript

let a = { first: "Tybalt", last: "Capulet" }

let b = {last: "Capulet" }

如何检查“ a”是否包含“ b”?

5 个答案:

答案 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。然后,您可以使用任何对象比较模块来检查combinedObja是否相等。

答案 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))