我确信已经有了一个答案以及一个"简单"的解决方案,但我在最后一个小时没有找到什么.

我有一个物体:

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

它显示了四个月的霍尔比赛的结果.我想从这个数组中创建一个具有以下 struct 的对象:

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

实际上,如果上面数组中的对象有switched: true,我想把switched["played"]的值增加1,它也有won: true,我想把键switched["won"]的值也增加1.反之亦然,对于switched: false,我想把结果对象中的所有内容都放在键put下.

我try 了一些相当尴尬的方法,reduce,但我认为一定有一个"更容易"的方法(我的根本没有工作…)

推荐答案

考虑到items保存着你的数据

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
    }
  }
);

Codesandbox link

Javascript相关问答推荐

有没有可能使滑动img动画以更快的速度连续?

为什么!逗号和空格不会作为输出返回,如果它在参数上?

从Node JS将对象数组中的数据插入Postgres表

如何使onPaste事件与可拖动的HTML元素一起工作?

Angular 订阅部分相互依赖并返回数组多个异步Http调用

更改预请求脚本中重用的JSON主体变量- Postman

TinyMCE 6导致Data:Image对象通过提供的脚本过度上载

在不扭曲纹理的情况下在顶点着色器中旋转UV

在JS/TS中将复杂图形转换为数组或其他数据 struct

如何在FiRestore中的事务中使用getCountFromServer

CSS网格使页面自动滚动

如何将PNG图像放在wix站点的Open Streemap map 上,使PNG图像成为 map 不可分割的一部分?

制表机表宽度在第一次加载时缩小,拖动后正在调整

如何使用属性访问器定义循环的for...的局部变量

Nextjs Google自动补全给出了不正确的值

无法在vue3中的img src上使用v-BIND

我怎样才能让我的时间停下来,这样我的精灵在时间到了之后就不会互相攻击了?

如何在拆分按钮Primeng 17中更改图标下拉菜单

当你点击数组时,如何在相应的元素中输出?

如何用JAVASCRIPT更新背景位置值来实现CSS视差滚动?