如何过滤不含ext键的对象?能否用reduce或filter实现?
过滤posts数组中不含ext键的对象:filter与reduce实现方案
问题描述
需要移除posts数组中不含ext键的对象(部分对象无关联图片),询问是否可以用reduce或filter方法实现该过滤需求。
示例数据:
{ "posts": [ { "filename": "1647706792183", "ext": ".png", "w": 300, "h": 450, "tn_w": 166, "tn_h": 250, "tim": 1664328637690788, "time": 1664328637, "md5": "Omk9VtmPOD1U38U1OOAP/w==", "fsize": 200271, "resto": 0, "country": "DK", "bumplimit": 0, "imagelimit": 0, "semantic_url": "f1-relentless-formula-one-general-all-smiles", "replies": 378, "images": 155, "unique_ips": 102, "tail_size": 50 }, { "now": "09/27/22(Tue)21:31:17", "name": "Anonymous", "resto": 123946553 } ] }
解决方案:两种方法都可以实现,具体如下
1. 使用filter方法(推荐,最简洁直观)
filter是数组专门的过滤方法,直接判断每个对象是否包含ext键即可。用hasOwnProperty能严谨排除原型链上的同名属性干扰:
// 假设data是你的原始数据对象 const filteredPosts = data.posts.filter(post => post.hasOwnProperty('ext'));
如果可以确定ext的值不会是null/undefined/false这类假值,也可以简化为:
const filteredPosts = data.posts.filter(post => post.ext);
2. 使用reduce方法
reduce通过累加器收集符合条件的元素,灵活性更强(如果后续需要同时处理其他逻辑,比如统计数量,reduce可以一步完成):
const filteredPosts = data.posts.reduce((result, post) => { if (post.hasOwnProperty('ext')) { result.push(post); } return result; }, []); // 初始值设为空数组,用来存放过滤后的结果
内容的提问来源于stack exchange,提问作者patatsci
相关产品推荐
相关产品推荐

