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

React.js中如何通过map方法遍历数组内所有对象并渲染数据

JSON数据渲染到页面的实现方案

你的接口返回的数据是包含单个对象的数组结构,map作为数组原生迭代方法完全适用,具体实现和替代方案如下:

方案1:使用map方法渲染

核心逻辑是先遍历外层数组,再将对象转为键值对数组后二次遍历生成DOM结构,原生JS实现示例:

// 接口返回的原始数据
const responseData = [{
    "Table_Name13": "64",
    "Table_Name14": "65",
    "Table_Name15": "66",
    "Table_Name16": "67",
    "Table_Name17": "68",
    "Table_Name18": "69",
    "Table_Name19": "71",
    "Table_Name20": "72",
    "Table_Name21": "73",
    "Table_Name22": "74",
    "Table_Name23": "75",
    "Table_Name24": "76",
    "Table_Name25": "77",
    "Table_Name26": "78",
    "Table_Name27": "79",
    "Table_Name28": "",
    "Table_Name29": "60",
    "Table_Name30": "",
    "Table_Name31": ""
}]

// 选取页面挂载容器
const container = document.getElementById('data-container')

// 生成渲染结构
const renderContent = responseData.map(item => {
  // 将对象转为[键, 值]数组后遍历生成单条字段结构
  const fieldList = Object.entries(item).map(([key, value]) => {
    // 空值兼容处理,不需要可以直接写${value}
    return `<li>${key}: ${value || '无数据'}</li>`
  }).join('')
  return `<ul>${fieldList}</ul>`
}).join('')

// 插入到页面
container.innerHTML = renderContent

如果是React/Vue等框架场景,直接返回对应JSX/模板结构即可,不需要手动拼接字符串和调用join方法。

方案2:不使用map的替代实现

  • 用for...of循环实现
const container = document.getElementById('data-container')
let htmlStr = ''
for (const item of responseData) {
  htmlStr += '<ul>'
  for (const [key, value] of Object.entries(item)) {
    htmlStr += `<li>${key}: ${value || '无数据'}</li>`
  }
  htmlStr += '</ul>'
}
container.innerHTML = htmlStr
  • 用forEach迭代实现
const container = document.getElementById('data-container')
let htmlStr = ''
responseData.forEach(item => {
  htmlStr += '<ul>'
  Object.entries(item).forEach(([key, value]) => {
    htmlStr += `<li>${key}: ${value || '无数据'}</li>`
  })
  htmlStr += '</ul>'
})
container.innerHTML = htmlStr
  • 调试场景快速打印完整JSON
    不需要拆分字段仅做展示时,直接用JSON.stringify格式化输出:
document.getElementById('data-container').textContent = JSON.stringify(responseData, null, 2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:24:03