我有一个对象数组,正在尝试使用过滤器和reduce来使输出正确显示。
它正在正确输出数据,但不是我想要的格式。任何输入都非常感谢。
当前输出
{
5: 12,
6: 15,
7: 12,
...
}
预期输出
{
session5-count: 12,
session6-count: 15,
session7-count: 12,
...
}
我确定这很简单,我还没有吃午饭,所以可能会阻碍我的思考过程。
这是我的公式和示例数据
更新功能
感谢 alex-g 和 zfrisch
const sessionsArray = [
{ session: '5', status: 'inactive' },
{ session: '5', status: 'inactive' },
{ session: '5', status: 'inactive' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '6', status: 'active' },
{ session: '6', status: 'active' },
{ session: '7', status: 'inactive' },
{ session: '7', status: 'inactive' },
{ session: '7', status: 'inactive' },
];
const filteredSessions = sessionsArray
.reduce( (acc, {session, status}) => {
if(status != 'active'){
acc["session-" + session ] = 0
}else{
acc["session-" + session ] =
acc["session-" + session ] + 1 || 1
}
return acc
}, {})
console.log(filteredSessions )
我正在尝试并使用THIS S.O. ANSWER来帮助格式化输出
答案 0 :(得分:2)
您可以使用模板字符串来获取所需的密钥格式。像这样:
const sessionsArray = [
{ session: '5', status: 'inactive' },
{ session: '5', status: 'inactive' },
{ session: '5', status: 'inactive' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '5', status: 'active' },
{ session: '6', status: 'active' },
{ session: '6', status: 'active' },
{ session: '7', status: 'inactive' },
{ session: '7', status: 'active' },
{ session: '7', status: 'active' },
];
const filteredSessions = sessionsArray
.filter(workshop => workshop.status === 'active')
.reduce( (acc, { session }) => {
acc[`session${session}-count`] = acc[`session${session}-count`] + 1 || 1;
return acc;
}, {});
console.log(filteredSessions)