You need to enable JavaScript to run this app. React Native 如何通过map方法向数组中添加指定结构的嵌套对象
优惠活动
大模型
产品
解决方案
定价
更多

React Native 如何通过map方法向数组中添加指定结构的嵌套对象

React Native 基于map方法的数组结构转换实现

已知条件

  • 源数组定义:
    var arr1 = [{key:0, ele: "A"}, {key:1, ele: "B"}]
  • 目标输出结构:
newarray = [
 {
  title: "@@@", 
  items: [{here: "A"}, {here: "B"}]
 }
]

转换规则

  • 新数组首项的title字段固定为预设字符串值"@@@"
  • 新数组首项下的items集合,需将源数组每个元素的ele字段值,映射为集合内对应子对象的here字段值
  • 转换过程仅使用数组原生map方法完成,不引入额外依赖

实现代码

// 定义源数组
const arr1 = [{key:0, ele: "A"}, {key:1, ele: "B"}]

// 生成目标结构数组
const newarray = [
  {
    title: "@@@",
    // 遍历源数组组装items字段
    items: arr1.map(sourceItem => ({
      here: sourceItem.ele
    }))
  }
]

逻辑说明

  • 调用arr1.map遍历每个源数组元素,返回的{here: sourceItem.ele}会被组装成独立的新数组,直接赋值给items字段
  • 外层将固定值的title和生成的items封装为单个对象,放入数组后完全匹配目标结构
  • 生成的结构可直接适配React Native中SectionList组件的sections入参格式,无需额外二次处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.08 16:27:02