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

Discord.js v14读取JSON报错:TypeError: Cannot read properties of undefined (reading 'name')

修复Discord.js v14中读取JSON时的"Cannot read properties of undefined"错误

你编写的Discord.js v14代码运行时抛出错误:TypeError: Cannot read properties of undefined (reading 'name'),原代码如下:

const {SlashCommandBuilder} = require("discord.js");
const json = require("../sql.json")

const objId = 9

const filteredObj = json.filter((obj) => obj.id === objId)[0]
const name = filteredObj.name
const age = filteredObj.age
const id = filteredObj.id

module.exports = {
    data: new SlashCommandBuilder()
    .setName("id")
    .setDescription("Make id check"),
  async execute (client, interaction){
    await interaction.reply({content: `name: ${json.name}\nage: ${json.age}\nid: ${json.id}`});
},
};

错误原因

  1. 无匹配对象时的未定义访问:如果json数组中不存在id=9的对象,filter()会返回空数组,取索引[0]得到undefined,此时访问filteredObj.name直接报错。
  2. 变量引用错误:execute函数中错误使用了原数组json的属性(json.name),但json是数组而非单个对象,应该使用筛选后的filteredObj。

修复方案

const { SlashCommandBuilder } = require("discord.js");
const json = require("../sql.json");

const objId = 9;

// 用find替代filter[0],找到第一个匹配项就停止遍历,更高效
const filteredObj = json.find((obj) => obj.id === objId);

module.exports = {
  data: new SlashCommandBuilder()
    .setName("id")
    .setDescription("Make id check"),
  async execute(client, interaction) {
    // 先判断是否找到匹配对象,避免未定义报错
    if (!filteredObj) {
      return await interaction.reply({ content: `未找到id为${objId}的对象` });
    }
    // 使用筛选后的单个对象属性
    await interaction.reply({
      content: `name: ${filteredObj.name}\nage: ${filteredObj.age}\nid: ${filteredObj.id}`
    });
  },
};

关键优化点

  • 用Array.find()替代filter()[0],提升遍历效率
  • 增加无匹配对象的判断逻辑,提前返回提示避免报错
  • 修正execute函数中的变量引用,确保使用筛选后的单个对象属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:01:07