ES6如何根据状态标识过滤数组对象并返回剩余数组?
解决方案
核心逻辑是:只针对指定name的对象根据对应状态决定是否保留,其他对象一律保留;如果没有需要移除的对象,直接返回原数组即可。
方法一:先判断是否需要过滤,再处理
// 假设原数组为 arr,状态变量为 xstatus、ystatus、zstatus const needFilter = !xstatus || !ystatus || !zstatus; if (!needFilter) { // 所有状态都为true,无需过滤,直接返回原数组 return arr; } // 需要过滤时,生成新数组 const result = arr.filter(item => { switch(item.name) { case 'is_xstatus': return xstatus; case 'is_ystatus': return ystatus; case 'is_zstatus': return zstatus; default: // 非目标name的对象直接保留 return true; } }); return result;
方法二:直接过滤,按需返回原数组
如果不在意是否创建新数组(所有状态为true时filter会生成和原数组内容一致的新数组),可以简化成:
const filtered = arr.filter(item => { if (item.name === 'is_xstatus') return xstatus; if (item.name === 'is_ystatus') return ystatus; if (item.name === 'is_zstatus') return zstatus; return true; }); // 若没有元素被过滤,返回原数组(避免不必要的数组复制) return filtered.length === arr.length ? arr : filtered;
为什么之前的方法出问题?
- 用filter返回空数组:应该是你的过滤条件只针对那三个指定
name的对象,且状态为false时把它们全过滤了,但没考虑数组里其他name的对象,加上默认返回true的逻辑就能解决。 - forEach+delete:delete只能把数组元素设为undefined,不会缩短数组长度,遍历后数组会有空占位,而且操作原数组容易引发其他问题,不如filter生成新数组更安全干净。
内容的提问来源于stack exchange,提问作者dragonfly
相关产品推荐
相关产品推荐

