Search code examples
javascriptnode.jsjsondiscorddiscord.js

Json TypeError: Cannot read properties of undefined (reading 'name')


I have an error where it says

TypeError: Cannot read properties of undefined (reading 'name')

I am making a Discord bot with NodeJS and Discord.js and I have an empty JSON where I add an item whenever I type a command but I can't get the values of that new item with the second I made I don't know why

    {
    "Scammere" : [

    ]
}
module.exports = {
    name: 'addscammer',
    description: "this is a ping command",
    execute(message, args, Discord){

        if(!args[0]) { return message.reply("Du skal skrive personens ingame navn"); }

        if(message.member.roles.cache.has('850790004275019796') || message.member.roles.cache.has('850790306915942400')){

            const jsonData= require('./test.json');

            var playerIsNew = true;

            for (let index = 0; index < jsonData.Scammere.length; index++) {
                const element = jsonData.Scammere[index];
                if(element.name.toUpperCase() == args[0].toString().toUpperCase()){ 
                    playerIsNew = false;
                    console.log("Person Findes Allerde"); 
                }
            }

            var LocalStorage = require('node-localstorage').LocalStorage,
            localStorage = new LocalStorage('./scratch');

            index = 0;

            

            for (let i = 0; i < jsonData.Scammere.length; i++) {
                const element = jsonData.Scammere[i].name.toString();
                if(element.toString().toUpperCase() == args[0].toUpperCase()){
                    index = i;
                    console.log(element + "is using" + i);
                }else{
                    index = jsonData.Scammere.length + 1;
                }
            }

            console.log(index);

            if(jsonData.Scammere.at(index) != null){
                console.log("Test");
                playerIsNew = false;
            }




            if(playerIsNew){
                var myObj = {
                    "name" : args[0],
                    "timesScamed" : 1,
                    "timesTrusted" : 0
                };    
                jsonData.Scammere.push(myObj);
            }else{
                jsonData.Scammere.at(index).timesScamed = parseInt(localStorage.getItem("storedScams " + jsonData.Scammere.at(index).timesScamed));
                jsonData.Scammere[index].timesScamed += 1;
            }

            console.log(jsonData.Scammere);
            
            setTimeout(() => {
                var hexColor = "#000";
                var status = "scammer";
                
                if(!playerIsNew){
                    if(jsonData.Scammere[index].timesScamed > jsonData.Scammere[index].timesTrusted){
                        hexColor = "#ff0000";
                        status = "Scammer"
                    }else{
                        hexColor = "#43eb34";
                        status = "Trusted";
                    }
                }else{
                    hexColor = "#c4c4c4";
                    status = "Måske";
                }
                const Test = new Discord.MessageEmbed().setColor(hexColor).setTitle("Data om: " + jsonData.Scammere[index].name.toString())
                .setAuthor({ name: jsonData.Scammere[index].name.toString(), iconURL: 'https://minotar.net/avatar/' + jsonData.Scammere.at(index).name.toString() + '/128.png', url: 'https://discord.js.org' })
                .setThumbnail('https://mc-heads.net/body/' + jsonData.Scammere.at(index).name.toString() + '/128.png')
                .addFields(
                    { name: 'Status', value: status },
                    { name: 'Scammet', value: jsonData.Scammere.at(index).timesScamed.toString() },
                    { name: 'Trusted', value: jsonData.Scammere.at(index).timesTrusted.toString() }
                );
            
                message.channel.send({ embeds: [Test] });
            }, 500);
        }   
    }
}

Solution

  • Your JSON of

        {
            "Scammere" : [
    
            ]
        }
    

    Is an object which has a single member called Scammere, which is an empty array.

    Your

    for (let index = 0; index < jsonData.Scammere.length; index++) {
    

    loop will never enter its content because jsonData.Scammere is empty, which means that it has a length of 0 and (0 < 0) is false.

    Yet, your line of

    const Test = new Discord.MessageEmbed().setColor(hexColor).setTitle("Data om: " + jsonData.Scammere[index].name.toString())
    

    expects jsonData.Scammere[index] to be an object that has a name field, but since jsonData.Scammere[index] does not exist, it is being evaluated to null and basically it turns out to be equivalent to null.name which throws your error.

    Solution

    If there is an item that you are not sure that it exists, then first check whether it exists and only if it does refer to its members/functions.