When dynamically accessed, the property of a JSON object is considered "undefined"

I'm running into trouble trying to access properties of a JSON object in my JavaScript code using obj[varWithPropName]. Strangely, it does work when I use obj["PropName"].

Here's a simplified snippet for reference:

import * as CharInfo from '../Configs/CharInfo.json';
(...)
this.ID = "Maya";

console.log("Maya" === this.ID); //true

console.log(typeof(CharInfo)); //object

console.log(CharInfo["Maya"]); //{configs: {…}, animations: {…}}

console.log(CharInfo[this.ID]); //undefined

The issue isn't limited to the console. In fact, when I try to access the property outside of console.log, it throws a runtime error:

Uncaught TypeError: Cannot read property 'animations' of undefined

Surprisingly, using the following syntax works:

CharInfo.default[this.ID]; //{configs: {…}, animations: {…}}

I'm curious to understand why this discrepancy exists rather than just finding a workaround. If anyone has encountered a similar problem before, I would greatly appreciate any insight! Thank you!

Answer №1

This solution should resolve the problem for you

Use this code snippet to import CharInfo from '../Configs/CharInfo.json'

The error likely stems from exporting the JSON in the CharInfo.json file as default. It may look something like this:

json = { /* your json */ };
export default json;

When importing, you might have used

`import * as CharInfo...`  

This imports everything from the file into a new variable CharInfo, with the default export json nested within the CharInfo object as CharInfo.default.

To access the actual json data directly as CharInfo, import it like

import CharInfo from '../Configs/CharInfo.json'
. This way, CharInfo[this.ID] will function as expected.

If you encounter any issues, feel free to ask for further assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to utilize the `useLoaderData` function in ReactRouter v6.9.0 within sibling components of the component where `loader()` is employed? If so, what is the method

In my MoviePage component, I have successfully fetched data using a loader and am utilizing this data with the help of useLoaderData. However, I am facing an issue when trying to access this data in sibling components such as MoviePage/Genre1, MoviePage/Ge ...

Issue with hasClass and addClass not working as expected

Why isn't the script below adding a class (.active) to .global-header when .navigation.primary has a class of .active? JS if($(".navigation.primary").hasClass("active")) { $('.global-header').addClass('active'); } HTML < ...

Tips for refreshing a GET request within a Vue.js application

I am receiving data from my Rails API backend and I would like to automatically refresh that GET request every 15 seconds. This way, if there are any changes on the backend (for example, if a POST request is made to another route), it will reload and retri ...

Is there a way for app.use to identify and match requests that begin with the same path?

Given that app.use() responds to any path that starts with /, why does the request localhost:3000/foo match the second method instead of the first? app.use("/",express.static('public'), function(req,res,next) { console.log(& ...

Implement the morgan express middleware from exports

For my logging needs in an Express application, I have decided to utilize the morgan package. Initially, I was able to integrate morgan by using it directly in my server.js file like so: app.use(morgan('tiny')), which worked perfectly. However, I ...

Tips for relocating a CSS button

I have designed two buttons using css and I am looking to align them below the title "forecast customer activity". Due to extensive styling in css, the code might appear lengthy. Requesting assistance with a solution after reviewing the following code snip ...

Disabling the default validation message in HTML form inputs

Is there a way to change the default message that appears when submitting an empty HTML text input? I would like the box border to turn red instead. Can anyone help me achieve this? Below is the code for the text input box: <div class="input-group ...

modifying output of data when onchange event is triggered

I am struggling with creating an onchange event for my option box in which the users of a site are listed. I have two input boxes designated for wins and losses, but the output is not changing when I select a user from the list. What could be wrong with my ...

What is the best way to restrict user input to specific numbers only?

I have a text input field, how can I ensure that only numeric values from 1 to 31 are allowed? <input type="number" min="1" max="31"> ...

Attempting to extract individual strings from a lengthy compilation of headlines

Looking for a solution to organize the output from a news api in Python, which currently appears as a long list of headlines and websites? Here is a sample output: {'status': 'ok', 'totalResults': 38, 'articles': [{ ...

Is it a good idea to steer clear of including OAuth tokens in the

Utilizing my OAuth2 token in my API program is essential. However, I am also keen on sharing my code through GitHub. How can I securely use my confidential token without including it directly in my source code? ...

Is the element loaded but not appearing on screen?

I am facing an issue when using ajax to send data to a PHP server and displaying it in the view. Even though the data loads successfully (checked in console), it does not display in the view. Can someone please help me resolve this? Here is my code : Vie ...

What steps should I take to fix the issue of "[ERR_REQUIRE_ESM]: Must use import to load ES Module" while working with D3.js version 7.0.0 and Next.js version 11.0.1?

Encountered a roadblock while integrating D3 with Next.js - facing an error when using D3.js v7.0.0 with Next.js v11.0.1: [ERR_REQUIRE_ESM]: Must use import to load ES Module Tried utilizing next-transpile-modules without success Managed to make D3.js ...

Conceal the button briefly when clicked

How can I disable a button on click for a few seconds, show an image during that time, and then hide the image and display the button again? HTML: <input type="submit" value="Submit" onclick="validate();" name="myButton" id="myButton"> <img st ...

Automatically update button appearance upon reaching zero value using JavaScript

Whenever I click the button, the user's HP decreases until it reaches 0 and then the button changes. However, a peculiar issue arises when the userHealth hits zero - the button does not change immediately. An additional click is required for the butto ...

Tips for Incorporating xmlhttp.responseText in If Statements

This is the code snippet from my save_custLog_data.php file: <?php $a = $_GET['custEmail']; $b = $_GET['pswrd']; $file = '/home/students/accounts/s2090031/hit3324/www/data/customer.xml'; if(file_exists($fi ...

Utilizing JavaScript to Incorporate Node Packages

Sorry for the basic question, as I am fairly new to web development and JavaScript. I am trying to utilize a package that I installed via npm called shopify-buy by following the instructions provided at: The package is located in my node_modules director ...

Retrieve the value of the second child element in a table cell when clicking on it with Javascript

I have created a table with one row that includes the title of the month and a cell containing an inner table with multiple rows and cells. I want to display the content of the second cell in the second table as a modal box or alert dialog when it is click ...

JavaScript: Troubleshooting Array Formatting

Seeking assistance with formatting this JavaScript array accurately. It seems like I am overlooking something crucial: Javascript: <script type="text/javascript"> var dimensions = new Array("225","320","480", "--"); var walls = new Array() ...

What methods are recommended for expanding the size of a select/dropdown menu?

Managing a long list of values can be challenging, especially when it continues to grow. Consider the following example: <select> <option value="1">1, some test</option> <option value="2">2, some text</option> <optio ...