动态筛选含undefined值的动态键对象数组,保留唯一对象
问题
我有一个格式如下的对象数组:
const myArray = [ { one: 'A', two: 'AB' }, { one: undefined, two: 'AB' }, { one: 'A', two: 'BC' }, { one: undefined, two: 'CC' }, ]
我需要筛选出符合特定规则的唯一对象数组:若某对象存在undefined值,但该对象非undefined的键值组合已在其他对象中存在,则忽略该对象。示例输出如下:
const outputMyArray = [ { one: 'A', two: 'AB' }, { one: 'A', two: 'BC' }, { one: undefined, two: 'CC' }, ]
注意:对象的键是动态生成的,无法硬编码,且每个对象的键数量一致。
我尝试了以下代码,但未能实现需求:
const objectValuesList = myArray.map((obj: any) => Object.values(obj)) const uniqueStrigifiedList = Array.from(new Set( objectValuesList.filter((obj: any) => !obj.includes(undefined)).map((obj: any) => JSON.stringify(obj)) )) myArray?.filter((obj: any) => !uniqueStrigifiedList?.includes( String(Object.values(obj)) ))
该方案无法正确去重,会将所有对象视为唯一。
解决方案
核心思路
- 先收集所有无
undefined值对象的「非空键值组合特征」(用剔除undefined后的键值对序列化字符串作为唯一标识) - 遍历原数组时:
- 无
undefined的对象直接保留 - 含
undefined的对象,生成其「非空键值组合特征」,若该特征未在已收集的集合中出现则保留,否则忽略
- 无
实现代码
function filterDuplicateUndefinedObjects(arr) { // 收集所有无undefined对象的非空键值特征 const existingValidSignatures = new Set(); arr.forEach(obj => { const hasUndefined = Object.values(obj).includes(undefined); if (!hasUndefined) { const validEntries = Object.entries(obj).filter(([_, val]) => val !== undefined); existingValidSignatures.add(JSON.stringify(validEntries)); } }); // 筛选符合规则的对象 const result = []; arr.forEach(obj => { const hasUndefined = Object.values(obj).includes(undefined); if (!hasUndefined) { result.push(obj); } else { const currentSignature = JSON.stringify( Object.entries(obj).filter(([_, val]) => val !== undefined) ); if (!existingValidSignatures.has(currentSignature)) { result.push(obj); } } }); return result; } // 测试示例 const myArray = [ { one: 'A', two: 'AB' }, { one: undefined, two: 'AB' }, { one: 'A', two: 'BC' }, { one: undefined, two: 'CC' }, ]; const outputMyArray = filterDuplicateUndefinedObjects(myArray); console.log(outputMyArray);
代码说明
- 特征标识生成:用
Object.entries获取键值对,过滤掉值为undefined的项后序列化,确保动态键场景下,非空键值组合的唯一性判断准确 - 两次遍历逻辑:第一次遍历收集有效对象的特征,第二次遍历根据特征判断含
undefined的对象是否需要保留 - 修复原代码问题:避免了原方案中
String(Object.values(obj))导致的格式歧义,改用JSON.stringify保证特征字符串的唯一性
内容的提问来源于stack exchange,提问作者iCodeByte
相关产品推荐
相关产品推荐

