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

ReactJS中遍历键值对:无需额外map函数展示key数组

解决方案:利用map的索引匹配对应key值

嘿,这个问题其实很好解决!因为你的key数组和images数组是一一对应的(每个索引位置的元素都是配对的),所以完全不需要额外创建map函数,直接在遍历images的时候用索引来取key数组里的对应内容就行。

修改后的代码:

const equipos = [ 
  { 
    key: [ 'Real Madrid', 'Manchester United', 'Champions League', 'English Premier League', 'Bayern Munchen', 'Juventus', 'Arsenal', ], 
    images: [ 
      'http://as00.epimg.net/img/comunes/fotos/fichas/equipos/large/1.png', 
      'https://4.bp.blogspot.com/_Z_YWTFNHUvw/TQDBKNXdwcI/AAAAAAAACI0/COhwIG2PkFA/s320/Manchester-United%255B1%255D.png', 
      'http://www.stickpng.com/assets/images/5842fe06a6515b1e0ad75b3b.png', 
      'https://i.pinimg.com/originals/f1/44/fc/f144fc61d0b0ed7716d740aa9deefb07.png', 
      'https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/FC_Bayern_M%C3%BCnchen_logo_%282017%29.svg/1200px-FC_Bayern_M%C3%BCnchen_logo_%282017%29.svg.png', 
      'http://as00.epimg.net/img/comunes/fotos/fichas/equipos/large/29.png', 
      'https://i.pinimg.com/originals/98/32/8b/98328b1d64c5f93ef5eceea7586430d1.png', 
    ], 
  }, 
];

// 小修正:equipos是数组,要取第一个元素的images,原代码的console.log(equipos.images)会返回undefined
console.log(equipos[0].images)

const IconosSeccion = () => ( 
  <div className="containerIconosSeccion"> 
    <div className="parentIconos" /> 
    {equipos.map(equipo => ( 
      <div> 
        {equipo.images.map((image, index) => ( // 新增index参数
          <div className="backgroundIconoIndependiente"> 
            <img alt={equipo.key[index]} className="iconoIndependiente" src={image} /> 
            <span className="textoIconoIndependiente">{equipo.key[index]}</span> {/* 用索引匹配对应key值 */}
          </div> 
        ))} 
      </div> 
    ))} 
  </div> 
);

关键说明:

  • map函数的第二个参数是当前元素的索引值,因为你的key和images数组长度完全一致,所以每个image对应的索引index,正好可以用来获取equipo.key[index]的文本内容,完美实现一一对应。
  • 顺便提个小细节:原代码里的console.log(equipos.images)是错误的,因为equipos是一个包含单个对象的数组,要访问内部的images应该用equipos[0].images。

这样修改后,每个图片下方的span就会自动显示对应的球队/赛事名称,完全不需要额外的map函数,高效又简洁~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:48:19