js中的对象数组:删除重复项 [英] Array of objects in js: remove duplicates

查看:101
本文介绍了js中的对象数组:删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个对象的数组:

I have an array with a number of objects:

[{"firstName":"an","lastName":"something","linkedInID":"..."},{"firstName":"stefanie","lastName":"doe","linkedInID":"..."},{"firstName":"john","lastName":"something","linkedInID":null},{"firstName":"timmy","lastName":"test","linkedInID":null},{"firstName":"john","lastName":"something","linkedInID":null}, ... ]

它是可能有重复,我希望将其删除。

It's possible that there are duplicates, and I wish to remove them.

这<答案得到了我的意思,我可以删除基于姓氏的重复项:

This answer got my to the point were I can remove duplicates based on the last name:

var arr = {};

for ( var i=0, len=attendees_in_one_array.length; i < len; i++ )
    arr[attendees_in_one_array[i]['lastName']] = attendees_in_one_array[i];

attendees_in_one_array = new Array();
for ( var key in arr )
    attendees_in_one_array.push(arr[key]);

我只想在firstName,lastName和linkedInID完全相同时删除一个人。

I only want a person to be removed when firstName, lastName and linkedInID is the exact same.

我试过更改 arr [attendees_in_one_array [i] ['lastName']] = attendees_in_one_array [i]; arr [attendees_in_one_array [i] ['lastName']&& attendees_in_one_array [i] ['firstName']&& attendees_in_one_array [i] ['linkedInID']] = attendees_in_one_array [i]; 但这不起作用。

I've tried changing arr[attendees_in_one_array[i]['lastName']] = attendees_in_one_array[i]; to arr[attendees_in_one_array[i]['lastName'] && attendees_in_one_array[i]['firstName'] && attendees_in_one_array[i]['linkedInID']] = attendees_in_one_array[i]; but that didn't work.

任何可以帮助我的人用这个?

Anyone who can help me with this?

推荐答案

你可以从3个值的组合形成唯一键

You can form the unique key from the combination of the 3 values

firstName + lastName + linkedInID

赞这个:

var arr = [{"firstName":"an","lastName":"something","linkedInID":"..."},{"firstName":"stefanie","lastName":"doe","linkedInID":"..."},{"firstName":"john","lastName":"something","linkedInID":null},{"firstName":"timmy","lastName":"test","linkedInID":null},{"firstName":"john","lastName":"something","linkedInID":null} ]

var ulist = {}, uarr =[];
arr.forEach(function(k) { ulist[k.firstName + k.lastName + k.linkedInID] = k; });
for(var i in ulist) uarr.push(ulist[i]);

// uarr contains your desired result 

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

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