Underscore.js,根据键值删除对象数组中的重复项
问题描述:
我有以下JS数组:
var myArray = [{name:"Bob",b:"text2",c:true},
{name:"Tom",b:"text2",c:true},
{name:"Adam",b:"text2",c:true},
{name:"Tom",b:"text2",c:true},
{name:"Bob",b:"text2",c:true}
];
我想消除名称值重复的索引,并重新创建一个新的数组,具有不同的名称,例如:
I want to eliminate the indexes with name value duplicates and recreate a new array, with distinct names, eg:
var mySubArray = [{name:"Bob",b:"text2",c:true},
{name:"Tom",b:"text2",c:true},
{name:"Adam",b:"text2",c:true},
];
如你所见,我删除了Bob和Tom,只留下3个不同的名字。这是否可能与下划线?如何?
As you can see, I removed "Bob" and "Tom", leaving only 3 distinct names. Is this possible with Underscore? How?
答
使用 _。uniq
进行自定义转换,像 _。property('name')
将会很好地或只是'name'
,作为@Gruff Bunny在评论中指出:
Use _.uniq
with a custom transformation, a function like _.property('name')
would do nicely or just 'name'
, as @Gruff Bunny noted in the comments :
var mySubArray = _.uniq(myArray, 'name');