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
相关产品推荐
相关产品推荐

