比较两个对象中存在的属性

Compare properties that exist in both objects

我有两个对象:

var a = {
  world: 'Mamba',
  planet: 'Oliver'
}

var b = {
  world: 'Koko'
}

如何只比较两个对象中都存在的属性?在我的示例中,它将是 属性 "world".

使用下划线:

您可以获取两个对象的键(使用 Object.keys), do an intersection (using _.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 
    }
});

演示版

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 += ('<li id=' + c + '>' + c + '</li>');
});

common.forEach(function(key) {

  var elem = document.getElementById(key);
  if (a[key] === b[key]) {
    elem.innerHTML += ' [equal]';
  } else {
     elem.innerHTML += ' [not equal]';  
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<h3>Common Properties</h3>
<ul id="list">
  <ul>

使用香草 JS:

你可以遍历a的所有属性,检查它是否存在于b中,然后比较:

for(var prop in a) {
    if(a.hasOwnProperty(prop) && b.hasOwnProperty(prop) && a[prop] === b[prop]) {
        // they are equal
    }
}

注意:使用 hasOwnProperty 不包括通过原型可用的属性。

演示版

var a = {
  world: 'Mamba',
  planet: 'Oliver',
  test: 'x'
};

var b = {
  world: 'Koko',
  test: 'x'
};

var list = document.getElementById('list');
for (var prop in a) {
  
  if (a.hasOwnProperty(prop) && b.hasOwnProperty(prop)) {
  
    list.innerHTML += '<li id="' + prop + '">' + prop + '</li>';

    var elem = document.getElementById(prop);
    if (a[prop] === b[prop]) {
      elem.innerHTML += ' [equal]';
    } else {
      elem.innerHTML += ' [not equal]';
    }
  }
}
<h3>Common Properties</h3>
<ul id="list">

</ul>


就 运行 时间而言,香草 JS 方式更高效

原因是它只迭代 a 的属性一次。

下划线方式需要获取对象键(需要iteration over each object),然后通过键数组再次迭代找到交集,然后在交集上再次迭代比较。

如果你使用下划线Js,那对你来说会很容易。 Underscore 有一个方法(_.intersection),它遍历对象或数组。

 var intersection=_.intersection(keys(a),keys(b));
 console.log(intersection);  // ["world"]
 $.each(intersection,function(index,value){
   if(a[value] == b[value])
     //write your code
});

否则先求对象交集,迭代匹配数组匹配相关值

var a = {
  world: 'Mamba',
  planet: 'Oliver'
}

var b = {
  world: 'Koko'
}
var arr = [];

// Find the matched keys in array(Intersection of keys)

$.each(Object.keys(a), function(index1, value1) {
  $.each(Object.keys(b), function(index2, value2) {
    if (value1 == value2)
      arr.push(value1)
  });

});

//Then iterate over array of keys to find matched value.

$.each(arr, function(index, value) {
  if (a[value] == b[value])
  // write your code.
});