skip to Main Content

code

if (interaction.commandName === 'comp-scrambles') {

        let datascrams = {};
        
        fs.readFile('scrambles.json', 'utf8', function(err, rawData){
            let datascrams = rawData;
        })
        const replyscrams = datascrams[interaction.options.getString('cube')]['scrams'];

        interaction.reply(replyscrams);
 
    }

JSON:

{
  "3x3": [
    {
      "scrams": "das"
    }
  ]
}

I expect it to go to my JSON file and go in the cube depth, and then the scrambles and take that. But it says

C:UsersLogan AltOneDriveDesktopKinchServer Comp Botsrcindex.js:479
        const replyscrams = datascrams[interaction.options.getString('cube')]['scrams'];
                                                                             ^

TypeError: Cannot read properties of undefined (reading 'scrams')
    at Client.<anonymous> (C:UsersLogan AltOneDriveDesktopKinchServer Comp
``` which is the error message

2

Answers


  1. The json you used as an example has "scrams" inside an array,

    {
      "3x3": [ //here
        {
          "scrams": "das"
        }
      ]
    }
    

    that would make your variable be:

    const replyscrams = datascrams[interaction.options.getString('cube')][0]['scrams'];
    

    added [0], or any index you need, after datascrams[interaction.options.getString('cube')] and before ['scrams']

    Login or Signup to reply.
  2. You could improve your code this way:

    Code

    if ( interaction.commandName === 'comp-scrambles' ) {
        // Read File Sync
        const datascrams = fs.readFileSync( 'scrambles.json', { encoding: 'utf8' } ) || {};
    
        // Get Cube Variable
        const interactionCube = interaction?.options?.getString('cube') || null;
    
        // Chain ands to determine if structure exits
        const replyscrams = datascrams && datascrams[ interactionCube ] && datascrams[ interactionCube ][0] && datascrams[ interactionCube ][0].scrams || null;
    
        // Send reply
        interaction.reply( replyscrams );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search