gpt4 book ai didi

javascript - 格式化对象数组输出

转载 作者:行者123 更新时间:2023-11-30 14:14:49 25 4
gpt4 key购买 nike

我有一组对象,我试图在使用过滤器和减少后使输出正确显示。

它正在正确输出数据,但不是我想要的格式。非常感谢任何输入。

电流输出

{
5: 12,
6: 15,
7: 12,
...
}

预期输出

{
session5-count: 12,
session6-count: 15,
session7-count: 12,
...
}

我敢肯定这是一件非常简单的事情,而且我还没有吃午饭,所以可能会阻碍我的思考过程。

这是我的公式和示例数据

更新的功能

感谢 alex-gzfrisch

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帮助格式化我的输出

最佳答案

您可以使用模板字符串来获取所需的 key 格式。像这样:

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)

关于javascript - 格式化对象数组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com