比较数组中的对象 [英] Compare objects in an array
问题描述
我有一个对象数组.
var array = [obj1, obj2, obj3, objN]
每个对象都有3个属性键,名称,描述.
every objects has 3 properties key, name, description.
如何比较这些对象是否相等,如果两个对象具有相同的键,则它们相等.
How can i compare these objects for equality, two objects are equal if they have the same key.
但是,如果有一个说四个对象,那么它们都必须具有相同的键才能相等.
But if a have lets say 4 objects they all must have the same key to be equal.
推荐答案
You can do that using Array.prototype.every()
:
every()
方法测试数组中的所有元素是否通过提供的功能实现的测试. (mdn)
The
every()
method tests whether all elements in the array pass the test implemented by the provided function. (mdn)
示例:
var array = [obj1, obj2, obj3, objN];
var allTheSame = array.every(function(element){
return element.key === array[0].key;
});
请注意, Array.prototype.every()
是IE 9+.但是,在mdn页面上有一个很好的 polyfill 用于IE的较早版本.
Please note that Array.prototype.every()
is IE 9+. However, there's a nice polyfill on the mdn page for older versions of IE.
如果您真的想使用for循环,可以这样做:
If you really want to use a for loop, you could do it like this:
var array = [obj1, obj2, obj3, objN];
var allTheSame = array.length == 1;
for(var i = 1; i < array.length && (array.length > 1 && allTheSame); i++){
allTheSame = array[0].key == array[i].key;
}
尝试以下用途:
[{key:1},{key:1},{key:1}]; // true
[{key:1},{key:1},{key:2}]; // false
[{key:1},{key:2},{key:1}]; // false
[{key:1}]; // true
这篇关于比较数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!