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

Node.js中如何基于FirstDate与LastDate组合对对象数组分组?

基于FirstDate+LastDate组合分组的实现方案

Lodash 实现(项目已安装依赖,优先使用)

Lodash 提供的_.groupBy可直接基于自定义规则聚合数组,代码量最少:

const _ = require('lodash')
// 拼接两个属性作为分组唯一标识,加`|`分隔符避免不同属性组合产生歧义键
const grouped = _.groupBy(data, item => `${item.FirstDate}|${item.LastDate}`)

注意:分组键添加|作为分隔符,是为了避免极端场景下不同属性组合拼接出相同字符串的歧义(例如FirstDate为a、LastDate为b和FirstDate为ab、LastDate为空的情况),当前使用固定格式日期的场景下可直接拼接两个属性值。

输出嵌套数组形式

直接取分组对象的所有值即可得到符合要求的嵌套数组:

const nestedResult = Object.values(grouped)

输出随机键分组对象

如果需要将原有日期组合键替换为随机字符串,可按如下转换:

// 引入Node内置crypto模块生成UUID作为随机键
const crypto = require('crypto')
const randomKeyResult = Object.fromEntries(
  Object.values(grouped).map(group => [crypto.randomUUID(), group])
  // 若需要按random1/random2这种顺序键,替换map的键为`random${index+1}`即可,加个index参数:
  // Object.values(grouped).map((group, index) => [`random${index+1}`, group])
)

原生JavaScript实现(无依赖)

通过数组reduce方法手动维护分组容器,逻辑与groupBy完全一致:

const grouped = data.reduce((acc, item) => {
  const groupKey = `${item.FirstDate}|${item.LastDate}`
  if (!acc[groupKey]) acc[groupKey] = []
  acc[groupKey].push(item)
  return acc
}, {})

// 转嵌套数组
const nestedResult = Object.values(grouped)

// 转随机键分组对象
const crypto = require('crypto')
const randomKeyResult = Object.fromEntries(
  Object.values(grouped).map(group => [crypto.randomUUID(), group])
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 00:45:04