本文介绍了与对象的javascript数组不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实有这种物体

var j = [{'one':1},{'two':2},{'three':3},{'four':4},{'five':5},{'one':1}];

现在,我想跳过重复的记录.有人可以建议我吗?

Now I want to skip the duplicate record. Can anyone suggest me the way?

推荐答案

一种用于过滤具有多个属性的对象的通用解决方案.

A generic solution to filter out objects with multiple properties.

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();

将无法比较第一个或第二个属性,因为对象的属性在javascript中不按顺序排列.我们可以做的就是使用属性进行比较.

It won't be possible to compare first or second property as the properties of an object is not in order in javascript. What we can do is compare using property.

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"]);

http://jsbin.com/ahijex/4/edit

这篇关于与对象的javascript数组不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 07:16