gpt4 book ai didi

javascript - 在对象数组中计算胜利、游戏和游戏类型并创建对象对象

转载 作者:行者123 更新时间:2023-12-05 01:50:24 26 4
gpt4 key购买 nike

我确信已经有一个答案以及一个“简单”的解决方案,但我在过去一小时内没有找到任何东西。

所以我有这个对象:

[
{
"win": false,
"switched": false
},
{
"win": false,
"switched": false
},
{
"win": true,
"switched": true
},
{
"win": true,
"switched": true
}
]

它显示了四场 monty-hall 游戏的结果。我想从此数组创建一个具有以下结构的对象:

{
switched: {
played: 2,
won: 2
},
put: {
played: 2,
lost: 2
}
}

所以实际上如果上部数组中的对象有 switched: true 我想将 switched["played"] 的值增加 1 并且它还有 won: true 我想将 switched["won"] 键的值也增加一。 switched: false 反之亦然,我希望将结果对象中的所有内容都放在 put 键下。

我用 reduce 尝试了一些相当尴尬的方法,但我认为必须有一种“更简单”的方法(我的方法根本不起作用......)

最佳答案

const items = [{
win: false,
switched: false
},
{
win: false,
switched: false
},
{
win: true,
switched: true
},
{
win: true,
switched: true
}
];

const res = items.reduce(
(acc, cur) => {
// If your current item is switched
return cur["switched"]
? { // ... deal with the switched part, leave the rest as is
...acc,
switched: {
played: acc.switched.played + 1, // increase the played counter by 1, based on whatever your accumulator currently has
won: acc.switched.won + Number(cur.win) // cast your win property to number (true -> 1, false -> 0) and increase accordngily
}
}
: { // ... otherwise deal with the put part, leave the rest as is
...acc,
put: {
played: acc.put.played + 1,
lost: acc.put.lost + Number(!cur.win) // negate your win so that it reflects a loss, cast to number and increase accordingly
}
};
},
// Initialize your accumulator
{
switched: {
played: 0,
won: 0
},
put: {
played: 0,
lost: 0
}
}
);

console.log(res);

关于javascript - 在对象数组中计算胜利、游戏和游戏类型并创建对象对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73140020/

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