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

如何将平面对象数组转换为React Native SectionList所需的分组结构

解决方案

方案1:基于你已用到的Lodash实现

你对Lodash groupBy 的使用思路是对的,只需要额外对分组后的对象做一次遍历转换即可保留日期键:

import { groupBy } from 'lodash';

// 原始接口返回的扁平交易数据
const rawTransactions = [/* 你的接口返回数据 */];

// 第一步:按日期分组,得到键为日期、值为对应交易数组的对象
const groupedByDate = groupBy(rawTransactions, 'date');

// 第二步:转换为SectionList要求的数组结构,保留日期作为分组标题
const sectionListData = Object.entries(groupedByDate).map(([date, transactions]) => ({
  date,
  transactions
}));

方案2:原生JavaScript实现(无需引入Lodash)

如果不想引入额外依赖,可以直接用reduce方法完成分组转换:

const rawTransactions = [/* 你的接口返回数据 */];

const sectionListData = Object.entries(
  rawTransactions.reduce((acc, transaction) => {
    const date = transaction.date;
    // 不存在该日期分组时先初始化
    if (!acc[date]) acc[date] = [];
    acc[date].push(transaction);
    return acc;
  }, {})
).map(([date, transactions]) => ({ date, transactions }));

可选:日期排序处理

如果需要按日期倒序展示最新交易,可以在转换完成后加一层排序:

sectionListData.sort((a, b) => new Date(b.date) - new Date(a.date));

SectionList使用示例

拿到转换后的数据直接传入组件即可:

import { SectionList, Text, View } from 'react-native';

const TransactionList = () => {
  return (
    <SectionList
      sections={sectionListData}
      keyExtractor={(item) => item.id.toString()}
      // 渲染分组头部
      renderSectionHeader={({ section }) => (
        <View style={{ padding: 8, backgroundColor: '#f5f5f5' }}>
          <Text style={{ fontWeight: 'bold' }}>{section.date}</Text>
        </View>
      )}
      // 渲染单条交易记录
      renderItem={({ item }) => (
        <View style={{ padding: 16, borderBottomWidth: 1, borderBottomColor: '#eee' }}>
          <Text>{item.title}</Text>
          <Text style={{ color: '#666', marginTop: 4 }}>{item.amount}</Text>
        </View>
      )}
    />
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:24:03