从数组中删除类似的对象 [英] Remove similar objects from array

查看:51
本文介绍了从数组中删除类似的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从具有4个相同值和1个唯一值的数组中删除objectt.

I'm trying to remove objectst from an array which have 4 identical values and 1 unique.

快速的Google搜索提供了很多选项,可以从数组中删除相同对象,但不能删除相似的对象.

A quick google search gives a lot of options for removing identical objects from an array, but not objects that are similar.

数组示例:

var data = [
   {Date: "2016-04-27T09:03:45Z", Name: "Tito", Title: "Developer", Department:"IT", Company: "XXX"},
   {Date: "2016-04-27T08:07:45Z", Name: "Tito", Title: "Developer", Department:"IT", Company: "XXX"},
   {Date: "2016-04-27T10:23:45Z", Name: "Tito", Title: "Developer", Department:"IT", Company: "XXX"}
]

我尝试过使用lodash的 _uniq 函数,但是只需要一个属性即可匹配:

I have tried using lodash _uniq function, but it only takes one property to match:

var non_duplidated_data = _.uniq(data, 'Name'); 

除日期外,所有值均相同.如何基于4个属性删除相同的对象?

All values are identical except date. How can I remove identical objects based on 4 properties?

推荐答案

您可以使用纯Javascript解决此问题.只需检查每个对象的每个属性:

You can solve this using plain Javascript. Just check each object for each property:

Array.prototype.allValuesSame = function() {
    for(var i = 1; i < this.length; i++) {
        if(this[i] !== this[0])
            return false;
    }
    return true;
}

var data = [
   {Date: "2016-04-27T09:03:45Z", Name: "Tito", Title: "Developer", Department:"IT", Company: "XXX"},
   {Date: "2016-04-27T08:07:45Z", Name: "Tito", Title: "Developer", Department:"IT", Company: "XXX"},
   {Date: "2016-04-27T10:23:45Z", Name: "Tito", Title: "Developer", Department:"IT", Company: "XXX"}
]

var tmpPropValues = {};
for (var property in data[0]) {
    tmpPropValues[property] = [];

    for(var i = 0; i < data.length; i++) {
        var obj = data[i];

    // store temporary in array
    if (obj.hasOwnProperty(property)) {
      var value = obj[property];

      tmpPropValues[property].push(value);
    }
  }

    if(tmpPropValues[property].allValuesSame()) {
      delete tmpPropValues[property];
  }
}

for(var prop in tmpPropValues) {
    var tmp = document.getElementById("result").innerHTML;
  document.getElementById("result").innerHTML = tmp+" "+prop;

}

我为您制作了小提琴.

这篇关于从数组中删除类似的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆