我有两个对象:
var a = { world: 'Mamba', planet: 'Oliver' } var b = { world: 'Koko' }
如何只比较两个对象中存在的属性?在我的例子中,它将是属性"世界".
您可以获取两个对象的键(使用Object.keys),对它们执行交集(使用_.intersect)并迭代它们并比较:
var keys1 = Object.keys(a); var keys2 = Object.keys(b); var common = _.intersection(keys1, keys2); common.forEach(function(key) { if(a[key] === b[key]) { // they are equal } });
DEMO
var a = {
world: 'Mamba',
planet: 'Oliver',
test: 'x'
};
var b = {
world: 'Koko',
test: 'x'
};
var keys1 = Object.keys(a);
var keys2 = Object.keys(b);
var common = _.intersection(keys1, keys2);
var list = document.getElementById('list');
common.forEach(function(c) {
list.innerHTML += ('' + c + ' ');
});
common.forEach(function(key) {
var elem = document.getElementById(key);
if (a[key] === b[key]) {
elem.innerHTML += ' [equal]';
} else {
elem.innerHTML += ' [not equal]';
}
});
Common Properties