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

React代码数据处理后出现undefined的原因及解决方法咨询

undefined出现的诱因

你的过滤逻辑存在疏漏:const others1 = data.filter((d) => d["1"]?.others !== "")仅排除了others为空字符串的条目,但数据中的Person6等条目不存在"1"属性,此时d["1"]?.others返回undefined,undefined !== ""的判断结果为真,这类条目会被保留进others1数组。
后续reduce统计时,你用c["1"]?.others作为对象key,对应值就是undefined,最终统计对象red会多一个key为undefined的属性,渲染到页面就会显示undefined。

解决方法

方案1:修改过滤逻辑,从根源避免无效条目

调整filter判断条件,同时校验对应属性存在且others不为空即可:

// 过滤出有"1"属性且others不为空的条目
const others1 = data.filter((d) => d["1"] && d["1"].others !== "");
// 同理处理others2
const others2 = data.filter((d) => d["2"] && d["2"].others !== "");

修改后没有对应属性的条目会被直接过滤,reduce统计时不会再产生undefined的key。

方案2:渲染阶段过滤无效key

如果不想修改原有过滤逻辑,也可以在转字符串渲染时跳过key为undefined的项:

function objToString() {
  let str = "";
  for (const [p, val] of Object.entries(red)) {
    // 跳过key为undefined的项
    if (p === "undefined") continue;
    str += `${p}:${val}\n`;
  }
  return str;
}

额外说明:你当前定义的objToString函数参数obj没有被实际使用,函数内直接调用了外部变量red,如果需要复用该函数处理red2等其他统计对象,可以修改为使用传入的参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:51:03