在对象数组中,过滤相等的对象。 (所有属性均匹配)

时间:2019-11-01 12:18:33

标签: javascript lodash

const timings = [
  {startH: 10, startM: 20, endH: 11, endM: 30},
  {startH: 10, startM: 20, endH: 11, endM: 30},
  {startH: 9, startM: 10, endH: 11, endM: 30},
  {startH: 10, startM: 20, endH: 10, endM: 30},
  {startH: 10, startM: 20, endH: 11, endM: 30},
  {startH: 10, startM: 20, endH: 11, endM: 30}
];

返回数组中所有相等的对象

1 个答案:

答案 0 :(得分:1)

尝试使用下一个代码:

const timings = [
  {startH: 10, startM: 20, endH: 11, endM: 30},
  {startH: 10, startM: 20, endH: 11, endM: 30},
  {startH: 9, startM: 10, endH: 11, endM: 30},
  {startH: 10, startM: 20, endH: 10, endM: 30},
  {startH: 10, startM: 20, endH: 11, endM: 30},
  {startH: 10, startM: 20, endH: 11, endM: 30}
];
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 uniqueObject = timings.uniqueObjects(["startH", "startM", "endH", "endM"]);

console.log(uniqueObject);