javascript - 有没有办法对这个对象数组进行分组或减少

标签 javascript arrays sorting javascript-objects

下面的示例,获取与 period_str 的相同值相对应的总数学值关键。

[
     {math: 40, period_str: "Period 1, 03 2019"},
     {math: 32, period_str: "Period 1, 03 2019"},
     {math: 44, period_str: "Period 1, 02 2020"},
]

预期输出

[
{math: 72, period_str: "Period 1, 03 2020"}
{math: 44, period_str: "Period 1, 02 2020"}
]

或者 输出(仅对象)

{math: 72, period_str: "Period 1, 03 2020"}
{math: 44, period_str: "Period 1, 02 2020"}

最佳答案

您可以仅使用period_str作为唯一键:

const arr = [
 {math: 40, period_str: "Period 1, 03 2019"},
 {math: 32, period_str: "Period 1, 03 2019"},
 {math: 44, period_str: "Period 1, 02 2020"},
]

const out = arr.reduce((a, v) => {
  if(a[v.period_str]) {
    a[v.period_str].math += v.math
  } else {
    a[v.period_str] = v
  }
  return a
}, {})

console.log(Object.values(out))

关于javascript - 有没有办法对这个对象数组进行分组或减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60077405/

相关文章:

javascript - 为什么此 <input type="range> slider 会跳过 100 个项目中的前 10 个?

javascript - 如何使用 Node.js 过滤掉 XML Node ?

c - 如何在C中使用循环在字符数组中输入一个字符?

javascript - 单击按钮后如何逐个调用部分并且上一节将隐藏?

javascript - 未捕获的语法错误 : Unexpected token < in React

javascript - 如何在javascript中将整数数组转换为字符串而不丢失方括号

jquery - 多个子数组中特定索引处的值的总和/平均值 - jQuery

python - 在 Python 中排序的最快方法

c++ - 通过两个参数对指针 vector 进行排序

python - 根据属性对对象进行排序