我确实有这种对象
var j = [{'one':1},{'two':2},{'three':3},{'four':4},{'five':5},{'one':1}];
Run Code Online (Sandbox Code Playgroud)
现在我想跳过重复的记录.有谁能建议我的方式?
过滤掉具有多个属性的对象的通用解决方案.
var list = [{'one':1},{'two':2},{'four':4},{'one':1},{'four':4},{'three':3},{'four':4},{'one':1},{'five':5},{'one':1}];
Array.prototype.uniqueObjects = function(){
function compare(a, b){
for(var prop in a){
if(a[prop] != b[prop]){
return false;
}
}
return true;
}
return this.filter(function(item, index, list){
for(var i=0; i<index;i++){
if(compare(item,list[i])){
return false;
}
}
return true;
});
}
var unique = list.uniqueObjects();
Run Code Online (Sandbox Code Playgroud)
编辑:
由于javascript中对象的属性不是有序的,因此无法比较第一个或第二个属性.我们可以做的是使用属性进行比较.
Array.prototype.uniqueObjects = function (props) {
function compare(a, b) {
var prop;
if (props) {
for (var j = 0; j < props.length; j++) {
prop = props[j];
if (a[prop] != b[prop]) {
return false;
}
}
} else {
for (prop in a) {
if (a[prop] != b[prop]) {
return false;
}
}
}
return true;
}
return this.filter(function (item, index, list) {
for (var i = 0; i < index; i++) {
if (compare(item, list[i])) {
return false;
}
}
return true;
});
};
var uniqueName = list.uniqueObjects(["name"]);
var uniqueAge = list.uniqueObjects(["age"]);
var uniqueObject = list.uniqueObjects(["name", "age"]);
Run Code Online (Sandbox Code Playgroud)
http://jsbin.com/ahijex/4/edit
| 归档时间: |
|
| 查看次数: |
8626 次 |
| 最近记录: |