You need to enable JavaScript to run this app. JavaScript如何基于CSV空单元格对关联数据进行分组
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何基于CSV空单元格对关联数据进行分组

实现方案

方案1:基于你已生成的初始对象数组处理

直接用Array.reduce遍历你转换好的locations数组,缓存当前生效的地点分组即可:

// locations 是你已经转换得到的初始对象数组
const groupedResult = locations.reduce((groups, currentItem) => {
  // 当前条目有地点信息,新增一个分组
  if (currentItem.location) {
    groups.push({
      location: currentItem.location,
      date: currentItem.date,
      persons: []
    })
  }
  // 将当前人员信息追加到最新的分组中
  groups.at(-1).persons.push({
    name: currentItem.name,
    surname: currentItem.surname
  })
  return groups
}, [])

方案2:直接从二维原始数据处理

可以跳过先转初始对象数组的步骤,直接处理原始二维数组,性能更好:

const [headers, ...lines] = [
  ["location",  "date",       "name",   "surname" ],
  ["New York",  "10/10/2021", "Max",    "Payne"   ],
  ["",          "",           "Duke",   "Nuken"   ],
  ["",          "",           "Jack",   "Carver"  ],
  ["Las Vegas", "30/10/2021", "Leon",   "Kennedy" ],
  ["",          "",           "Donkey", "Kong"    ],
  ["",          "",           "Ryu",    "Hayabusa"],
]

const groupedResult = lines.reduce((groups, line) => {
  const [location, date, name, surname] = line
  // 碰到非空地点就新建分组
  if (location) {
    groups.push({ location, date, persons: [] })
  }
  // 人员加入最新分组
  groups.at(-1).persons.push({ name, surname })
  return groups
}, [])

异常兼容说明

如果你的原始数据存在首行location为空的异常场景,可以在操作分组前增加判断避免报错:

// 在push人员前增加校验
if (!groups.length) {
  throw new Error('首条数据缺少location信息,无法分组')
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 20:36:04