如何映射对象数组

时间:2019-12-10 16:13:12

标签: javascript arrays object

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

我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用reduce函数根据每个对象的可见属性进行递增。我们的默认值为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);