删除对象数组中的重复项

时间:2017-04-06 15:17:13

标签: javascript angularjs arrays object duplicates

actions: { fooAction({commit, getters}, data) { commit('FOO_MUTATION', {data, getters}) } }, mutations: { FOO_MUTATION(state, {data, getters}) { console.log(getters); } } 中的数据如下所示:

$scope.filteredShows

我正在使用此数据使用[{"id":19,"show_name":"The Walking Dead","show_type":"Series","show_date":"Sun, Feb 26 2017","orig_date":"2017-02-26","season":"7","ep_val":"11","episode":"Season 7, Episode 11","watched":false}, {"id":20,"show_name":"The Walking Dead","show_type":"Series","show_date":"Sun, Mar 5 2017","orig_date":"2017-03-05","season":"7","ep_val":"12","episode":"Season 7, Episode 12","watched":false}, {"id":21,"show_name":"The Walking Dead","show_type":"Series","show_date":"Sun, Mar 12 2017","orig_date":"2017-03-12","season":"7","ep_val":"13","episode":"Season 7, Episode 13","watched":false}, {"id":22,"show_name":"The Walking Dead","show_type":"Series","show_date":"Sun, Mar 19 2017","orig_date":"2017-03-19","season":"7","ep_val":"14","episode":"Season 7, Episode 14","watched":false}] 填充select班级:

ng-options

但是有一个以上的“行尸走肉”一集被列出,因此它在下拉列表中列出了4次“行尸走肉”。如何删除此数组中的重复项?

4 个答案:

答案 0 :(得分:0)

你可以试试这个:

ng-options='show.show_name for show in filteredShows track by show.show_name'

或者您可以尝试使用underscore.js的_.uniq()方法

答案 1 :(得分:0)

为什么不简单地在只包含相关数据点的范围内构建一个新数组......你可以这样做:

const tmp = {} //Tmp var to store show_name's
$scope.showsOnly = $scope.filteredShows.filter(s => 
    tmp[s.show_name]?0:(tmp[s.show_name] = 1)
)

这会按名称过滤所有内容(并且只允许show_name的一个实例。)

答案 2 :(得分:0)

如果您使用的是lodash,可以使用_.uniqBy():

执行此操作
_.uniqBy(data ,"show_name") 

了解更多信息:https://lodash.com/docs/4.17.4#uniqBy

答案 3 :(得分:0)

I think you can try groupBy filter in ng-repeat.

ng-options="show.show_name for show in filteredShows track by show.id | groupBy: 'show_name'"