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

ReactJS实现带分组标题的对象数组数据映射问题

实现按日期分组渲染对象数组的方案

嘿,这个需求其实挺常见的,可能你搜索的关键词没踩对~我来给你一步步拆解实现方法,不管你用原生JS还是前端框架都能套用:

第一步:把时间戳转换成对应的分组标签(Today/Tomorrow/具体日期)

首先需要一个工具函数,将传入的时间戳转换成我们想要的分组名称(比如Today、Tomorrow,或者其他日期的格式化字符串),核心是对比目标日期和今天、明天的年月日:

function getDateGroup(timestamp) {
  const targetDate = new Date(timestamp);
  const today = new Date();
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);

  // 只比较年/月/日,忽略时分秒的差异
  const isToday = targetDate.getFullYear() === today.getFullYear() &&
                  targetDate.getMonth() === today.getMonth() &&
                  targetDate.getDate() === today.getDate();
  const isTomorrow = targetDate.getFullYear() === tomorrow.getFullYear() &&
                     targetDate.getMonth() === tomorrow.getMonth() &&
                     targetDate.getDate() === tomorrow.getDate();

  if (isToday) return 'Today';
  if (isTomorrow) return 'Tomorrow';
  // 其他日期返回 YYYY-MM-DD 格式的字符串
  return `${targetDate.getFullYear()}-${String(targetDate.getMonth()+1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`;
}

第二步:将原数组按日期分组

利用数组的reduce方法,把原始对象数组转换成以分组标签为键、对应对象列表为值的结构:

假设你的原始数据是这样的:

const originalData = [
  { date: "1716182400000", name: "Object One", description: "Object Description" },
  { date: "1716182400000", name: "Object Two", description: "Object Description" },
  { date: "1716268800000", name: "Object Three", description: "Object Description" },
  // 更多数据...
];

执行分组逻辑:

const groupedData = originalData.reduce((acc, item) => {
  const groupKey = getDateGroup(item.date);
  if (!acc[groupKey]) {
    acc[groupKey] = [];
  }
  acc[groupKey].push(item);
  return acc;
}, {});

第三步:渲染分组后的内容

原生JS渲染示例

如果用原生JS直接操作DOM:

// 获取页面上的容器元素
const container = document.getElementById('content-container');

// 对分组排序,保证Today在前,Tomorrow次之,其他日期按时间升序
const sortedGroups = Object.keys(groupedData).sort((a, b) => {
  const priority = { 'Today': 0, 'Tomorrow': 1 };
  if (priority[a] !== undefined && priority[b] !== undefined) {
    return priority[a] - priority[b];
  }
  // 其他日期按字符串排序(YYYY-MM-DD格式天然支持升序)
  return a.localeCompare(b);
});

// 遍历渲染每个分组
sortedGroups.forEach(group => {
  // 创建分组标题
  const heading = document.createElement('h3');
  heading.textContent = `${group}:`;
  container.appendChild(heading);

  // 创建对象列表
  const list = document.createElement('ul');
  groupedData[group].forEach(item => {
    const listItem = document.createElement('li');
    listItem.textContent = `${item.name} – ${item.description}`;
    list.appendChild(listItem);
  });
  container.appendChild(list);
});

React渲染示例

如果用React框架,逻辑类似,用组件化的方式渲染:

import { useMemo } from 'react';

// 先复用前面的getDateGroup函数
function getDateGroup(timestamp) {
  // 函数内容同上...
}

function GroupedObjects({ data }) {
  // 用useMemo缓存分组结果,避免重复计算
  const groupedData = useMemo(() => {
    return data.reduce((acc, item) => {
      const groupKey = getDateGroup(item.date);
      if (!acc[groupKey]) acc[groupKey] = [];
      acc[groupKey].push(item);
      return acc;
    }, {});
  }, [data]);

  // 缓存排序后的分组键
  const sortedGroups = useMemo(() => {
    const priority = { 'Today': 0, 'Tomorrow': 1 };
    return Object.keys(groupedData).sort((a, b) => {
      if (priority[a] !== undefined && priority[b] !== undefined) {
        return priority[a] - priority[b];
      }
      return a.localeCompare(b);
    });
  }, [groupedData]);

  return (
    <div className="grouped-objects-container">
      {sortedGroups.map(group => (
        <div key={group} className="date-group">
          <h3>{group}:</h3>
          <ul className="object-list">
            {groupedData[group].map((item, idx) => (
              <li key={idx} className="object-item">
                {item.name} – {item.description}
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  );
}

// 使用组件时传入数据:
// <GroupedObjects data={originalData} />

这样渲染后就能得到你想要的效果:

Today:

  • Object One – Object Description
  • Object Two – Object Description
    Tomorrow:
  • Object Three – Object Description

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:21:46