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

如何为React Native的SectionList转换对象数组结构?

Grouping Orders by Date in React Native

No problem! Here's a straightforward way to convert your flat order array into the grouped structure you need, complete with date titles:

Step 1: Create a Date Formatting Helper

First, we'll need a function to convert those Unix timestamps into your desired dd/mm/yyyy string format:

const formatDate = (timestamp) => {
  const date = new Date(timestamp);
  const day = date.getDate();
  const month = date.getMonth() + 1; // JavaScript months are 0-indexed, so add 1
  const year = date.getFullYear();
  return `${day}/${month}/${year}`;
};

Step 2: Group Orders by Formatted Date

Next, we'll use an object to group orders by their date string, then convert that object into your target array structure:

// Your original order array
const rawOrders = [
  { id: 1001, orderNo: 'abc', customer: 'John', date: 1524526218641 },
  { id: 1002, orderNo: 'def', customer: 'Ringo', date: 1524555627191 },
  { id: 1003, orderNo: 'ghi', customer: 'George', date: 1524555662611 },
  { id: 1004, orderNo: 'jkl', customer: 'Paul', date: 1524717318641 }
];

// Group orders into an object where keys are date strings
const groupedByDate = {};
rawOrders.forEach(order => {
  const dateKey = formatDate(order.date);
  // Initialize the array if the date key doesn't exist yet
  if (!groupedByDate[dateKey]) {
    groupedByDate[dateKey] = [];
  }
  groupedByDate[dateKey].push(order);
});

// Convert the grouped object to your desired array structure
const groupedOrders = Object.entries(groupedByDate).map(([title, data]) => ({
  title,
  data
}));

Step 3: Optional - Sort the Groups by Date

If you want the date groups to appear in chronological order, add a sort step before mapping:

const groupedOrders = Object.entries(groupedByDate)
  // Convert date strings to Date objects for proper sorting
  .sort(([dateA], [dateB]) => {
    // Convert dd/mm/yyyy to yyyy-mm-dd for valid Date parsing
    const parseDate = (str) => new Date(str.split('/').reverse().join('-'));
    return parseDate(dateA) - parseDate(dateB);
  })
  .map(([title, data]) => ({ title, data }));

What You'll Get

Running this code will produce exactly the structure you asked for:

[
  { title: '23/4/2018', data: [ { id: 1001, orderNo: 'abc', ... } ] },
  { title: '24/4/2018', data: [ { id: 1002, ... }, { id: 1003, ... } ] },
  { title: '26/4/2018', data: [ { id: 1004, ... } ] }
]

This works perfectly in React Native since it uses standard JavaScript, so you can drop this logic right into your component (maybe wrap it in a useMemo hook if you want to optimize re-renders!).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:38:20