使用Lodash统计对象中未读消息数量
使用Lodash统计对象中未读消息数量(seen: false)
这事儿我做消息通知功能时经常碰到,用Lodash处理起来超顺手,分两种常见场景给你拆解解决方案:
场景1:消息按分类存在对象的数组属性中
比如你的数据结构是分收件箱、垃圾邮件这类分类的:
const messages = { inbox: [ { id: 1, content: "周末一起打球?", seen: false }, { id: 2, content: "项目进度更新", seen: true }, { id: 3, content: "快递取件通知", seen: false } ], spam: [ { id: 4, content: "限时特惠活动", seen: false }, { id: 5, content: "免费领取礼品", seen: true } ] };
解决方案:
先把所有分类的消息数组展平成一维数组,再统计未读数量:
// 方法1:过滤后取长度,直观易懂 const unreadCount = _.filter(_.flatMap(messages), { seen: false }).length; // 方法2:用sumBy直接累加,性能更优(不用生成新数组) const unreadCount = _.sumBy(_.flatMap(messages), msg => msg.seen ? 0 : 1);
场景2:消息是对象的直接属性值
如果消息直接以键值对形式存在对象中,比如:
const messages = { msg001: { id: 1, content: "会议提醒", seen: false }, msg002: { id: 2, content: "周报已提交", seen: true }, msg003: { id: 3, content: "代码评审请求", seen: false } };
解决方案:
先提取对象的所有值(也就是每条消息),再统计未读:
// 方法1:过滤计数 const unreadCount = _.filter(_.values(messages), { seen: false }).length; // 方法2:sumBy简化写法 const unreadCount = _.sumBy(_.values(messages), msg => !msg.seen ? 1 : 0);
额外补充:如果是单层消息数组
要是消息本来就是一个单层数组(没有分类对象包裹),那更简单:
const messages = [ { id: 1, content: "新评论通知", seen: false }, { id: 2, content: "点赞提醒", seen: true } ]; const unreadCount = _.filter(messages, { seen: false }).length; // 或者更简洁的sumBy写法 const unreadCount = _.sumBy(messages, msg => !msg.seen);
内容的提问来源于stack exchange,提问作者Saad Ahmed
相关产品推荐
相关产品推荐

