如何在TypeScript中根据嵌套对象的_id字段筛选唯一对象?
如何在TypeScript中根据嵌套字段筛选数组唯一对象?
给定如下TypeScript对象数组,需要根据group.application._id字段筛选出唯一对象,移除重复项(示例中第二个和第三个元素的group.application._id相同,需保留第二个、移除第三个):
const myObjArray: any = [ { "group": { "name": "SAM-admin", "active": true, "application": { "_id": "g4fac238hma10kjo3mv473vbs", "name": "Prism", "owners": "", "url": "", "description": "", "active": "", "created_by": "", "updated_by": "" }, "created_by": "", "updated_by": "", }, "user": "g4fac238hma10kjo3mv473vbs", "role": "g4fac238hma10kjo3mv473vbs", "isAdmin": true, "active": true, "created_by": "Abhilash.Shajan1@gmail.com", "updated_by": "", }, { "group": { "name": "SAM-super-admin", "active": true, "application": { "_id": "g4fac238hma10kjo3mv473asc", "name": "Utopia", "owners": "", "url": "", "description": "", "active": "", "created_by": "", "updated_by": "" }, "created_by": "", "updated_by": "", }, "user": "g4fac238hma10kjo3mv473asc", "role": "g4fac238hma10kjo3mv473asc", "isAdmin": true, "active": true, "created_by": "Hima.Thomas@gmail.com", "updated_by": "", }, { "group": { "name": "SAM-guest", "active": true, "application": { "_id": "g4fac238hma10kjo3mv473asc", "name": "Utopia", "owners": "", "url": "", "description": "", "active": "", "created_by": "", "updated_by": "" }, "created_by": "", "updated_by": "", }, "user": "g4fac238hma10kjo3mv473asc", "role": "g4fac238hma10kjo3mv473asc", "isAdmin": true, "active": true, "created_by": "Hima.Thomas@gmail.com", "updated_by": "", } ];
最简单的实现方式
推荐用Array.filter()结合临时对象追踪已出现的ID,一次遍历完成去重,性能更优:
// 记录已出现的application _id const seenAppIds: Record<string, boolean> = {}; // 过滤出唯一对象 const uniqueArray = myObjArray.filter(item => { const appId = item.group.application._id; if (!seenAppIds[appId]) { seenAppIds[appId] = true; return true; } return false; });
如果追求更简洁的写法,也可以用Array.reduce():
const uniqueArray = myObjArray.reduce((acc: any[], current) => { const appId = current.group.application._id; // 检查结果数组中是否已有该ID的对象 if (!acc.some(item => item.group.application._id === appId)) { acc.push(current); } return acc; }, []);
说明
filter+对象记录的时间复杂度是O(n),适合处理较大数组;reduce+some的时间复杂度是O(n²),小数据量下使用更简洁。- 两种方式都会保留每个
group.application._id第一次出现的对象,满足需求中移除第三个重复对象的要求。
内容的提问来源于stack exchange,提问作者Abhilash Shajan
相关产品推荐
相关产品推荐

