如何在JavaScript中根据条件移除对象数组中的重复对象
解决方案
你的需求是移除那些documentTypeId重复且对应flag为false的对象——也就是当同一个documentTypeId下存在flag: true的对象时,删掉该类型下所有flag: false的对象;如果某个documentTypeId下全是flag: false的对象,则保留它们。
问题分析
你当前的代码逻辑有误:findIndex会找到第一个documentTypeId相同且flag: false的元素索引,filter的条件是当前元素索引等于这个值,这会只保留第一个flag: false的重复项,完全不符合你的需求。
正确实现
可以分两步处理:
- 先收集所有存在
flag: true的documentTypeId集合 - 过滤数组:保留
flag: true的对象,或者flag: false但该类型没有flag: true对象的元素
代码如下:
const test = [{ "id": 100, "documentTypeId": 3, "docName": "test", "flag": false }, { "id": 31184688089, "documentTypeId": 1, "docName": "test2", "flag": true }, { "documentTypeId": 3, "docName": "test3", "flag": true, "active": true } ] // 收集所有存在flag=true的documentTypeId const hasTrueFlag = new Set(test.filter(item => item.flag).map(item => item.documentTypeId)); // 过滤数组 const res = test.filter(item => { // 保留flag为true的,或者flag为false但该类型没有true的对象 return item.flag || !hasTrueFlag.has(item.documentTypeId); }); console.log(res);
运行结果
输出的结果会是:
[ { id: 31184688089, documentTypeId: 1, docName: 'test2', flag: true }, { documentTypeId: 3, docName: 'test3', flag: true, active: true } ]
正好符合你想要的——移除了documentTypeId=3且flag=false的对象,保留了其余有效元素。
内容的提问来源于stack exchange,提问作者UIAPPDEVELOPER
相关产品推荐
相关产品推荐

