如何检查两个对象属性是否匹配?

时间:2016-12-14 02:34:13

标签: javascript

假设有两个对象,但是一个对象具有与另一个对象不同的属性。有没有办法弄清楚哪些属性匹配?

例如:

var objectOne = {
  boy: "jack",
  girl: "jill"
}


var objectTwo = {
  boy: "john",
  girl: "mary",
  dog: "mo"
}

编辑:它应该告诉我boygirl属性名称都可以在两个对象中找到。

6 个答案:

答案 0 :(得分:2)

var in_both = [];
for (var key in objectOne) { // simply iterate over the keys in the first object
    if (Object.hasOwnProperty.call(objectTwo, key)) { // and check if the key is in the other object, too
        in_both.push(key);
    }
}

C.f。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

现在,如果您想测试值是否相同,那么只需将更多代码添加到内部if的条件/主体中。

答案 1 :(得分:2)

使用Object.keys

Object.keys(objectOne).filter(k => Object.hasOwnProperty.call(objectTwo, k))

答案 2 :(得分:1)

您可以使用Object.keys并使用Array.prototype.reduce循环播放一次并列出常用密钥 - 请参阅下面的演示:



var objectOne={boy:"jack",girl:"jill"};
var objectTwo={boy:"john",girl:"mary",dog:"mo"};

var result = Object.keys(objectOne).reduce(function(p,c){
  if(c in objectTwo)
    p.push(c);
  return p;
},[]);

console.log(result);




答案 3 :(得分:1)

如果要查找给定两个对象的哪些键匹配,可以使用for... in循环遍历对象的所有键。在我的函数中,它将遍历键并返回两个对象中所有匹配键的数组。

let objectOne = {
  boy: "jack",
  girl: "jill"
}

let objectTwo = {
  boy: "john",
  girl: "mary",
  dog: "mo"
}

function matchingKeys (obj1, obj2) {
  let matches = [];
  let key1, key2;
  
  for (key1 in obj1) {
    for (key2 in obj2) {
      if ( key1 === key2) {
        matches.push(key1);
      }
    }
  }
  return matches
}

const result = matchingKeys(objectOne, objectTwo);
console.log(result)

答案 4 :(得分:0)

试试这个尺寸:

function compare(obj1, obj2) {
    // get the list of keys for the first object
    var keys = Object.keys(obj1);

    var result = [];

    // check all from the keys in the first object
    // if it exists in the second object, add it to the result
    for (var i = 0; i < keys.length; i++) {
        if (keys[i] in obj2) {
            result.push([keys[i]])
        }           
    }

    return result;
}

答案 5 :(得分:0)

这并不比这里的某些解决方案好,但我想我会分享:

function objectHas(obj, predicate) {
  return JSON.stringify(obj) === JSON.stringify({ ...obj, ...predicate })
}