javascript - 如何映射对象数组
问题描述
我有我的对象“消息”数组,我想计算“看到:1”的项目数
const messages = [
{ id: 66, seen:1, tourist_full_name: "Khouloud Ben Abddallah" },
{ id: 102, seen: 0, tourist_full_name: "Harry Paz Galvez" },
{ id: 103, seen: 0, tourist_full_name: "Harry Paz Galvez" },
{ id: 104, seen: 1, tourist_full_name: "Harry Paz Galvez" },
{ id: 105, seen: 1, tourist_full_name: "Harry Paz Galvez" }
];
例如在这里我想创建一个可以像这样的变量
var SeenCount=3 ;
我怎样才能做到这一点 ?
解决方案
使用reduce函数根据每个对象的 seen 属性递增。我们的默认值为 0,它会根据seen
属性值在循环的每次迭代中递增
const messages = [
{ id: 66, seen:1, tourist_full_name: "Khouloud Ben Abddallah" },
{ id: 102, seen: 0, tourist_full_name: "Harry Paz Galvez" },
{ id: 103, seen: 0, tourist_full_name: "Harry Paz Galvez" },
{ id: 104, seen: 1, tourist_full_name: "Harry Paz Galvez" },
{ id: 105, seen: 1, tourist_full_name: "Harry Paz Galvez" }
];
let a = messages.reduce((acc, item) => {
return acc + item.seen;
}, 0);
console.log(a);
推荐阅读
- java - Java Applet:为什么这个动画这么快,我怎样才能让它变慢
- java - 颜色渲染不正确
- ruby-on-rails - Rails ::module_name vs module_name 和模块在几个文件之间拆分
- actionscript-3 - Adobe Air 应用程序:在 Android 9 上 requestPermission() 后没有弹出窗口
- java - Android中是否有某种#define可以用来简化语句?
- android - 如何将数据保存在firebase父键中不是默认值
- ruby-on-rails - 设计自定义密码验证导致控制台中的无效用户
- php - 在 Concrete5 中从用户返回的数据在测试时不会评估为真
- android - 创建矢量图像资源时出错:
不支持 - javascript - 将类实例函数绑定到 v8::FunctionTemplate