一个属性的 JavaScript 数组总数

问题描述 投票:0回答:1

我看过很多例子,但无法让它发挥作用。最好的情况是,我最终得到了现有数组的一个版本,其中包含复制的属性,这些属性应该在摘要中丢失。

我想为每个位置输出一个新的总计数组,并且不包含特定期间、期间属性等的任何详细信息。 我认为我的问题是 Object.assign({}, o);我正在创建一个完整的副本,但我不知道如何仅创建一个仅包含可以添加总数的位置的对象。

这是一个简化的示例,在原始示例中,我对多列求和并删除多列。

let helper = {};
let locationPeriodCounts = [
  {"period": "2023-10-21", "location": "228", "countIn": 6},
  {"period": "2023-10-22", "location": "228", "countIn": 8},
  {"period": "2023-10-23", "location": "228", "countIn": 3},
  {"period": "2023-10-24", "location": "228", "countIn": 1},
  {"period": "2023-10-21", "location": "229", "countIn": 5},
  {"period": "2023-10-22", "location": "229", "countIn": 18},
  {"period": "2023-10-23", "location": "229", "countIn": 8},
  {"period": "2023-10-24", "location": "230", "countIn": 3},
  {"period": "2023-10-25", "location": "230", "countIn": 4}
];

let locationCounts = locationPeriodCounts.reduce(function(r, o) {
  let key = o.location;
  if (!helper[key]) {
    helper[key] = Object.assign({}, o); // create a copy of o
    helper[key].totalCount = 0;
    r.push(helper[key]);
  } else {
    helper[key].totalCount += o.countIn;
  }
  return r;
}, []);

console.log(locationCounts);

javascript reduce
1个回答
0
投票

如果没有预期的输出,很难猜测你想要什么。

我的猜测是这样的

let locationCounts = locationPeriodCounts.reduce(function(r, o) {
  let key = o.location;
  r[key] ??= 0;
  r[key] += o.countIn
  return r;
}, {});

console.log(locationCounts);
<script>
    let locationPeriodCounts = [
      {"period": "2023-10-21", "location": "228", "countIn": 6},
      {"period": "2023-10-22", "location": "228", "countIn": 8},
      {"period": "2023-10-23", "location": "228", "countIn": 3},
      {"period": "2023-10-24", "location": "228", "countIn": 1},
      {"period": "2023-10-21", "location": "229", "countIn": 5},
      {"period": "2023-10-22", "location": "229", "countIn": 18},
      {"period": "2023-10-23", "location": "229", "countIn": 8},
      {"period": "2023-10-24", "location": "230", "countIn": 3},
      {"period": "2023-10-25", "location": "230", "countIn": 4}
    ];

</script>

© www.soinside.com 2019 - 2024. All rights reserved.