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

使用map()遍历能获取行对象但无法访问其属性值的技术问题

问题排查与解决

问题根源

你遍历filtered的方式完全错误:

  • 你把filtered这个对象包装成了数组[filtered],然后对这个数组执行map,此时遍历的el是整个filtered对象(也就是你console.log(el)输出的包含所有团队的大对象),而非单个团队的统计数据。
  • 这个大对象本身没有nvCount、team这些属性,所以访问el.nvCount自然返回undefined。

修复方案

直接取filtered的值数组来遍历,用Object.values(filtered)获取每个团队的统计对象,再执行循环拼接表格行。

修正后的代码片段

let tableData = (
  '<table>' +
    '<thead>' +        
        '<th>Team</th>' +
        '<th>Non-Veg</th>' +
        '<th>Veg</th>' +
        '<th>Total</th>' +      
    '</thead>'
); 

// 修正遍历逻辑:取filtered的所有值组成数组后遍历
Object.values(filtered).forEach(el => {
  console.log(el); // 现在el是单个团队的统计对象,比如{ nvCount:2, team:'Greeters'... }
  console.log(el.nvCount); // 正常输出数值
  tableData += (
    '<tr>' +
      '<td>' + el.team + '</td>' +
      '<td>' + el.nvCount + '</td>' +
      '<td>' + el.vCount + '</td>' +
      '<td>' + (el.nvCount + el.vCount) + '</td>' + // 加括号避免字符串拼接
    '</tr>'
  );
});  

tableData +=  '</table>';

额外优化点

  • 原代码中nvCount + vCount会被当成字符串拼接(因为前后是字符串),必须加括号强制计算数值和:(el.nvCount + el.vCount)
  • 若不需要显示team为空的项(比如Media、Intercession),可以添加过滤逻辑:
    Object.values(filtered).filter(el => el.team).forEach(el => {
      // 拼接逻辑同上
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:45:48