本文介绍了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?

推荐答案

使用进行自定义转换,像将会很好地或只是'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');

和演示

这篇关于Underscore.js,根据键值删除对象数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:22