You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS如何将对象数组转换为指定格式的国家状态统计对象

实现方案

你可以直接用数组的reduce方法完成转换,因为题目已经明确不存在同一国家同一status的重复条目,不需要额外做去重判断,代码实现如下:

const dataFromDB = [
  {country: 'India', count: 2, status: 'Active'}, 
  {country: 'USA', count: 3, status: 'Recovered'}, 
  {country: 'India', count: 2, status: 'Recovered'}, 
  {country: 'Russia', count: 1, status: 'Active'},
  {country: 'India', count: 1, status: 'Dead'}, 
  {country: 'Brazil', count: 1, status: 'Active'}, 
  {country: 'Canada', count: 1, status: 'Dead'}, 
  {country: 'USA', count: 1, status: 'Active'}
]

const formatIWant = dataFromDB.reduce((result, item) => {
  // 把status转成小写匹配目标字段名
  const statusField = item.status.toLowerCase()
  // 新国家先初始化三个状态默认值为0
  if (!result[item.country]) {
    result[item.country] = {
      active: 0,
      dead: 0,
      recovered: 0
    }
  }
  // 赋值即可,要兼容后续可能的重复条目可以改成 +=
  result[item.country][statusField] = item.count
  return result
}, {})

执行完成后formatIWant就是你需要的输出格式。

内容的提问来源于stack exchange,提问作者cmgchess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 16:54:06