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

React Native:如何分组API返回数组项以构建SectionList?

解决React Native SectionList数据格式化问题

可以通过Array.reduce()结合Object.values()实现需求,以下是具体实现方案:

原始数据

const rawData = {
  "movies": [
    { "id": "1", "title": "Star Wars", "releaseYear": "1990" },
    { "id": "2", "title": "Back to the Future", "releaseYear": "1990" },
    { "id": "3", "title": "The Matrix", "releaseYear": "2010" },
    { "id": "4", "title": "Inception", "releaseYear": "2010" },
    { "id": "5", "title": "Interstellar", "releaseYear": "2010" }
  ]
};

格式化代码

// 用reduce按年份分组并构建目标结构
const grouped = rawData.movies.reduce((acc, movie) => {
  const year = movie.releaseYear;
  // 初始化对应年份的分组结构
  if (!acc[year]) {
    acc[year] = {
      releaseYear: year,
      data: []
    };
  }
  // 筛选所需属性,加入分组的data数组
  acc[year].data.push({
    id: movie.id,
    title: movie.title
  });
  return acc;
}, {});

// 将分组对象转为数组,得到最终格式
const formattedData = {
  movies: Object.values(grouped)
};

最终输出结构

{
  "movies": [
    {
      "releaseYear": "1990",
      "data": [
        { "id": "1", "title": "Star Wars" },
        { "id": "2", "title": "Back to the Future" }
      ]
    },
    {
      "releaseYear": "2010",
      "data": [
        { "id": "3", "title": "The Matrix" },
        { "id": "4", "title": "Inception" },
        { "id": "5", "title": "Interstellar" }
      ]
    }
  ]
}

代码说明

  • reduce()遍历原始电影数组,以年份为键构建临时分组对象,每个分组预设releaseYear和data字段
  • 遍历每个电影时,仅保留id和title属性,存入对应年份分组的data数组
  • 最后用Object.values()将分组对象的所有值提取为数组,得到SectionList所需的分组结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:15:41