Home > Enterprise >  Node.js TypeError: Cannot read property '1' of undefined
Node.js TypeError: Cannot read property '1' of undefined

Time:05-01

index.js

const o = require('./altoken')

    for(const i=1; i<99; i  ){
        
        if(o.opts[i].identity.username === null){break;}; //error here
        
        message.guild.channels.create(o.opts[i].identity.username, {type: "text",parent: id})
    }

altoken.js

 module.exports.opts1 = {
  mro: {
    as: false,
  },
  identity: {
    username: "x",
    password: "x"
  },
  krlo: [
    'x',
  ]
};

I want to create as many channels as modules in altoken.js but I am getting an error. TypeError: Cannot read property '1' of undefined

CodePudding user response:

You want to access a dynamic property name. You need bracket notation:

o['opts'   i]

Example:

const o = require('./altoken')

for(const i=1; i<99; i  ){
    
    if(o['opts'   i].identity.username === null){break;}; //error here
    
    message.guild.channels.create(o['opts'   i].identity.username, {type: "text",parent: id})
}

CodePudding user response:

You export opts1, not opts

if(o.opts1[i] ...)

Also, opts1 is not an array, so that is another issue. It will not be undefined, but also not iteratable.

This will give you array.

module.exports.opts1 = [
{
  mro: {
    as: false,
  },
  identity: {
    username: "x",
    password: "x"
  },
  krlo: [
    'x',
  ]
},
{
  mro: {
    as: true,
  },
  identity: {
    username: "b",
    password: "b"
  },
  krlo: [
    'z',
  ]
}
]

Finally, in javascript, start your arrays from index '0', not '1'

  • Related