Home > database >  TypeError: Cannot read properties of undefined (reading 'forEach') at Object.<anonymous
TypeError: Cannot read properties of undefined (reading 'forEach') at Object.<anonymous

Time:04-05

I'm really new to Javascript. So please bear with my garbage coding but I do not know what this error means and have spent really long trying to solve this. I am using Replit right now but I have also tried it on Visual Studio which gives the same error. Please help, I have no idea what to do!

Whenever I try to run my script it keeps erroring with this:

TypeError: Cannot read properties of undefined (reading 'forEach')
    at Object.<anonymous> (/home/runner/myrepl/index.js:10:6)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47

Here Is my Index.js:

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const {token} = require('./token.json');
var jsonconfig = require("./config.json")
var jsonconfig,DISCORD_ID
var CMDS = jsonconfig.CMDS

var prefix = 'p!'

args.forEach((a, b) => {
  args[b] = a.replace("`", "")

  args[b] = args[b].replace(".", "")

  args[b] = args[b].replace("`", "")
  args[b] = args[b].replace(`"`, "")

  args[b] = args[b].replace(`'`, "")

})
var args = Message.content.split(" ")
if (Message.author.bot == false) {
  if (Message.content.startsWith("$")) {

    if (Message.channel.id != CMDS && Message.author.id != DISCORD_ID) {
      Message.reply("stop using cmds here idiot. <#"   CMDS   ">")
    }
  }

  args.forEach((a, b) => {
    args[b] = a.replace("`", "")
    
    args[b] = args[b].replace(".", "")

    args[b] = args[b].replace("`", "")
    args[b] = args[b].replace(`"`, "")

    args[b] = args[b].replace(`'`, "")

        })
  switch (args[0]) {
    
    case prefix   "pois":

  var id = parseInt(args[1])
  if (id) {
    fetch(`https://www.rolimons.com/uaid/`   id).then(res => res.text()).then(res => {
      //// clog(res)
      if (res != 'Uaid not found, try again later') {
        var search = res,
          first = 'uaid_details'
        var second = `owner_list`;
        var itemdat = JSON.parse(search.substring(search.indexOf(first)   first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
        // clog(itemdat)
        var search = res,
          first = 'item_details'
        var second = `uaid_details`;
        var itemname = JSON.parse(search.substring(search.indexOf(first)   first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
        var search = res,
          first = 'owner_list'
        var second = `lucky_cat_uaid`;
        var owners = JSON.parse(search.substring(search.indexOf(first)   first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
        Message.reply(`Checking be patient bozo...`)
        var em = new discord.MessageEmbed()
        .setFooter("Archs")
      .setURL("https://www.rolimons.com/item/"   args[1])
        .setColor("#ffc0cb")
        .setThumbnail("https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid="   itemdat["asset_id"])
        .setTitle(`UAID `   args[1])
        .setURL(`https://www.rolimons.com/uaid/`   args[1])
        .setAuthor(itemname.name, `https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=`   itemdat["asset_id"])
      if (itemdat.serial) {
        em.addField('SERIAL', itemdat.serial)
          }
        em.addField('OWNER', (itemdat.owner_name || `Hidden/Deleted`))
        em.addField(`Last Traded`, itemdat["updated_relative_string"])
        Message.reply(em)
        if (itemdat["updated_relative_string"].search(`month`) != -1 || itemdat["updated_relative_string"].search(`year`) != -1) {
          Message.channel.send(`Since the current owner has had it for more than a month, we have deemed this uaid(${args[1]}) as CLEAN :white_check_mark:`)
          } else {
          comped_detected = false
          Object.keys(owners).forEach(x => {
            var item = owners[x][0]
            if (item && parseInt(x)   2628000 >= Date.now() / 1000) {
              fetch(`https://avatar.roblox.com/v1/users/${item}/avatar`).then(res => res.json().catch(err => { })).then(avatar => {
                avatar.assets.forEach(a => {
                  if (badassets[a.id] != undefined) {
                    comped_detected = true
                                                            }
                })
                fetch("https://inventory.roblox.com/v1/users/"   item   "/assets/collectibles?sortOrder=Asc&limit=100").then(res => res.json().catch(err => { })).then(p => {
                  // clog(p)
                  var amt = 0
                  if (p.data) {
                    p.data.forEach(l => {
                      amt = amt   itemdata[l.assetId][4]
                      })
                    if (amt < 5000) {
                      comped_detected = true
                    }
                  }
                })
              })
            }
          })
        }
      }
    }
  )}
  }
}

client
    .login(token)
    .catch(consola.error)

I have Node.js, discord.js, discord, and npm installed. My bot token is stored in token.json and my config (discord_ID and CMDS channel ID is stored in config.json).

I am trying to make it controlled from discord with a command like "p!". I don't know this problem at all.

CodePudding user response:

You are trying to iterate through the args array (args.forEach()) before var args exists. If you move var args = Message.content.split(" ") just after var prefix = 'p!' (before your loop) then the issue presented should be solved. I couldn't say whether your code will then 'work', but it is why you are getting the error

CodePudding user response:

One of the issues that I see from the get-go is, you are iterating args before you declare the variable

--> iteration args.forEach((a, b) => {
  args[b] = a.replace("`", "")

  args[b] = args[b].replace(".", "")

  args[b] = args[b].replace("`", "")
  args[b] = args[b].replace(`"`, "")

  args[b] = args[b].replace(`'`, "")

})
 --> declaration var args = Message.content.split(" ")

it should be the other way around, like that:

--> declaration var args = Message.content.split(" ")

--> iteration args.forEach((a, b) => {
 args[b] = a.replace("`", "")

 args[b] = args[b].replace(".", "")

 args[b] = args[b].replace("`", "")
 args[b] = args[b].replace(`"`, "")

 args[b] = args[b].replace(`'`, "")

})

second this that i noticed is, .split is a method used on strings and forEach is a method used on arrays

strictly for the error -

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

that error means that you can not iterate an undefined variable. mainly because, as I explained up here, you try to iterate args before declaring such a variable. although, in order to you .forEach(), args must be an Array.

perhaps you could try and give more details? perhaps a link to a repository or at least show the data structure that you are using

CodePudding user response:

You currently have args.forEach((a, b).. twice. Before and after defining args. Remove the first one.

  • Related