通过带下划线的属性值过滤重复的集合对象(不区分大小写和修剪) [英] Filter duplicate collection objects (case-insenstive and trim) by property value with underscore

查看:28
本文介绍了通过带下划线的属性值过滤重复的集合对象(不区分大小写和修剪)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来根据所选属性的值过滤/拒绝集合中的对象.具体来说,我需要过滤掉包含所选属性重复值的对象.我需要将属性值转换为小写并修剪空格.

I'm looking for a way to filter / reject objects in a collection based on the value of a chosen property. Specifically I need to filter out objects that contain duplicate values for that chosen property. I need to convert the property value to lower case and trim the whitespace.

我已经有了删除重复项的方法,但我不知道如何包含小写转换和修剪.

I already have my method for removing the duplicates but I can't figure out how to include the lowercase conversion and the trim.

removeDuplicates: function (coll, attr) {
      var uniques = _.map(_.groupBy(coll, function (obj) {
        return obj[attr];
      }), function (grouped) {
        return grouped[0];
      });

      return uniques;
    }

任何帮助将不胜感激.

推荐答案

如果集合是这样定义的

var array = [{
    name: "thefourtheye"
}, {
    name: "theFOURtheye"
}, {
    name: "thethirdeye"
}];

你应该使用 _.uniq 函数,就像这样

You should be using _.uniq function, like this

var attr = "name";
console.log(_.unique(array, false, function(currenObject) {
    return currenObject[attr].toLowerCase();
}));
# [ { name: 'thefourtheye' }, { name: 'thethirdeye' } ]

根据签名,

uniq_.uniq(array, [isSorted], [iterator])

第二个参数是判断集合是否已经排序.这很重要,因为如果对集合进行排序,则存在可以非常有效地找到唯一数据的算法.

the second parameter is tell if the collection is already sorted. This is important, because if the collection is sorted, there are algorithms which can find the unique data very efficiently.

第三个参数,应该是一个函数,可以对数据进行变换,得到要比较的键值.正如我们在示例中看到的,我们实际上从各个对象中选择了 name 属性并将它们转换为小写字母.因此,这个小写名称将代表这个对象,如果两个小写名称相同,那么这些对象将被视为彼此重复.

the third parameter, should be a function, which can transform the data to get the key value to compare. As we see in the example, we actually pick the name property from the individual objects and convert them to lower case letters. So, this lower cased name will represent this object and if two lowercased names are the same, then those objects will be considered as the duplicate of each other.

这篇关于通过带下划线的属性值过滤重复的集合对象(不区分大小写和修剪)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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