下划线/ lodash由多个属性唯一 [英] underscore/lodash unique by multiple properties

查看:377
本文介绍了下划线/ lodash由多个属性唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有重复项的对象数组,我正在尝试获得一个唯一的列表,其中唯一性由对象属性的子集定义。例如,

  {a:1,b:1,c:2} 

我想在唯一性比较中忽略 c 。 / p>

我可以做类似的事情

  _。uniq(myArray,function (element){return element.a +_+ element + b}); 

我希望能做到

  _。uniq(myArray,function(element){return {a:element.a,b:element.b}}); 

但这不起作用。有没有像我能做的那样,或者如果我要比较多个属性,我是否需要创建一个可比较的对象表示?

解决方案

遗憾的是,似乎没有一种直接的方法可以做到这一点。如果没有为此编写自己的函数,则需要返回可以直接比较相等的内容(如第一个示例中所示)。



一种方法是只需 .join()您需要的属性:

  _。 uniqBy(myArray,function(elem){return [elem.a,elem.b] .join();}); 

或者,您可以使用 _。选择 _。省略 删除您不需要的内容。从那里,您可以使用 _。值使用 .join(),甚至只需 JSON.stringify

  _。uniqBy(myArray,function(elem){
返回JSON.stringify(_。pick(elem,['a','b']));
});

请注意,就物业订单而言,物品不具有确定性,因此您可能只想坚持使用显式数组方法。



PS将<$> c $ c> uniqBy 替换为<$> c> c> uniq Lodash< 4


I have an array of objects with duplicates and I'm trying to get a unique listing, where uniqueness is defined by a subset of the properties of the object. For example,

{a:"1",b:"1",c:"2"}

And I want to ignore c in the uniqueness comparison.

I can do something like

_.uniq(myArray,function(element) { return element.a + "_" + element+b});

I was hoping I could do

_.uniq(myArray,function(element) { return {a:element.a, b:element.b} });

But that doesn't work. Is there something like that I can do, or do I need to create a comparable representation of the object if I'm comparing multiple properties?

解决方案

There doesn't seem to be a straightforward way to do this, unfortunately. Short of writing your own function for this, you'll need to return something that can be directly compared for equality (as in your first example).

One method would be to just .join() the properties you need:

_.uniqBy(myArray, function(elem) { return [elem.a, elem.b].join(); });

Alternatively, you can use _.pick or _.omit to remove whatever you don't need. From there, you could use _.values with a .join(), or even just JSON.stringify:

_.uniqBy(myArray, function(elem) {
    return JSON.stringify(_.pick(elem, ['a', 'b']));
});

Keep in mind that objects are not deterministic as far as property order goes, so you may want to just stick to the explicit array approach.

P.S. Replace uniqBy with uniq for Lodash < 4

这篇关于下划线/ lodash由多个属性唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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