首页 > 解决方案 > 如何映射对象数组

问题描述

我有我的对象“消息”数组,我想计算“看到: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 ;

我怎样才能做到这一点 ?

标签: javascriptarraysobject

解决方案


使用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);


推荐阅读