假设有两个对象,但其中一个对象的属性与另一个对象不同。有没有办法找出哪些属性匹配?
例如:
var objectOne = {
boy: "jack",
girl: "jill"
}
var objectTwo = {
boy: "john",
girl: "mary",
dog: "mo"
}
编辑:它应该告诉我在两个对象中都找到了 boy
和 girl
属性名称。
最佳答案
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
的条件/主体添加更多代码即可。
关于javascript - 如何检查两个对象属性是否匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133898/