Error: Cannot access property 'tb' of an undefined value

While running the Application, I encountered an error in the declaration of constants.ts file where I was assigning data from a json file to constant variables.

In the json file named object.json, I had some data structured like this:

{
 "furniture": {
     "tb": {
         "value": "table",
         "display": "Table(s)"
      },
      "ch": {
        "value": "chair",
        "display": "Chair(s)"
     }
 },

 "furnitureTypes": [
    {
     "value": "LivingRoomSofa",
     "display": "Living Room Sofa"
    },
    {
     "value": "CoffeeTable",
     "display": "Coffee Table"
    },
   {
    "value": "AccentCabinet",
    "display": "Accent Cabinet"
   }
 ],

"boardes": [
      {
       "value": null,
       "display": "--"
      },
      {
       "value": "Blockboard",
       "display": "Block board"
      },
      {
       "value": "Foamboard",
       "display": "Foam board"
      },
      {
       "value": "Fiberboard",
       "display": "Fiber board"
      }
  ]
}

Next, I created a constants.ts file and imported the above json data like this:

import * as objData from './objects.json';

In the constants.ts file, I used the imported data to create constant variables like this:

import * as objData from './objects.json';

const obj = <any>objData;

console.log('obj---:',obj);

export const Constants = { farr : [obj.furniture.tb, obj.furniture.ch]; }

When I ran the project, I encountered an error message that said:

Cannot read property 'tb' of undefined at Module../src/app/shared/constants.ts

The console log displayed this information:

obj-- Module {default: {…}, __esModule: true, Symbol(Symbol.toStringTag): "Module"}

I'm wondering why it is showing Module and adding a default key instead of directly displaying the json object data.

What I need is for the console log to show the json object directly like this:

json-obj----------: 
  {farr: Array(2), furnitureTypes: Array(3), boardes: Array(4), …}
   boardes: (4) [{…}, {…}, {…}, {…}]
  farr: (2) [{…}, {…}]
  furniture: {tb: {…}, ch: {…}}
  furnitureTypes: (3) [{…}, {…}, {…}]
  __proto__: Object

Here I should be able to access data directly like obj.tarr.a and obj.tripTypes[0]

However, in my case, the console log is displaying the data like this:

obj---: 
 Module {default: {…}, __esModule: true, Symbol(Symbol.toStringTag): 
 "Module"}
default:
   boardes: (4) [{…}, {…}, {…}, {…}]
   furniture: {tb: {…}, ch: {…}}
   furnitureTypes: (3) [{…}, {…}, {…}]
   __proto__: Object
   Symbol(Symbol.toStringTag): "Module"
   __esModule: true

It seems to be showing Module rather than an Object.

How can I get it to display as an Object?

If anyone has any solutions to this problem, please help me out.

Answer №1

To start, the first step is to generate a file with the extension .ts (e.g. example.ts) and within that file example.ts, include the following code:

export default {
  "furniture": {
    "tb": {
      "value": "tables",
      "display": "Table(s)"
    },
    "ch": {
      "value": "chairs",
      "display": "Chair(s)"
    }
  }
}

Next, you will need to import this file into your component:

import obj from './example';

For a demonstration, check out this Live Demo.

By following these steps, you can expect everything to work as intended.

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

What is the correct way to end this jQuery statement?

I've been working on this for about 6 hours now. I ran it through multiple Lint tools and various other online tests, but I just can't seem to get the statement below to close properly. There's a persistent error showing up on the last line ...

Get a compressed folder from jszip containing a PDF file that is either empty or blank

I'm facing a challenge with my Vue app where I need to compress a group of PDF files in a folder using JSZip. While testing with just one file, the zip downloads successfully but when I try to open the PDF file inside it, the content appears blank. I ...

Angular is not able to access the value of a promise in a different function after it has been retrieved

I have a form with default values that should be added to the form fields when it appears. There are two functions: #1 for fetching data from the backend and #2 for displaying the form: person$: any; ngOnInit() { this.getPersonData(123) this.buildPer ...

Binding iframes in Angular 6

Is there a way to display iframe code stored in a variable within a div? Here's the HTML code: <div class="top-image" [innerHTML]="yt"></div> And here's the TypeScript code: yt = '<iframe class="w-100" src="https://www.you ...

"Unlock the secret to effortlessly redirecting users to a designated page when they click the browser's back

So I'm facing the challenge of disabling the browser back button on multiple routes and sending requests to the backend is resulting in inconsistent behavior. I don't want to create a multitude of similar API requests each time. Currently, I have ...

How to return a variable to Express when clicking a button?

Imagine having a list of 10 elements, each with a unique id as their name, and the user has the ability to add more items to the list at any time. If I were to click on an element, my goal is to have Express retrieve the id of that specific element. If it ...

Unable to retrieve Angular Service variable from Controller

I am facing an issue with my Angular Service. I have set up two controllers and one service. The first controller fetches data through an AJAX call and stores it in the service. Then, the second controller tries to access this data from the service. While ...

Is it possible to retrieve the width value when using layout=fill in next/image?

<Image alt="image_example" src="/image_example.png" layout="fill" objectFit="none" /> <Test width={?} height={?}/> I developed a straightforward component using next/image. I am interest ...

ngx-bootstrap - Not Triggering On Hide Event

Having trouble triggering a function in my Angular component when closing a modal from ngx-bootstrap. No matter what method I use, I can't seem to catch the event. The event I want to trigger is simple - just need to see it in the console for now: // ...

Leveraging LevelGraph with MemDOWN

I've been experimenting with using LevelGraph and MemDOWN together, but I've noticed that my put and get queries are significantly slower compared to using the filesystem directly with LevelUP. It seems like there might be some mistake in my setu ...

Retrieve the URL of the previously visited webpage using Javascript

Is there a way to retrieve the URL of the last visited page using JavaScript? I want to be able to track which product the user viewed most recently. I have attempted the following code: var x = document.referrer; document.getElementById("demo").innerHTML ...

Tips on preventing duplicate websocket clients in VueJS

Each time I access a component, it triggers the socket.on event. Additionally, there is a Vuejs button component as shown below. So when I emit to the 'socket.on('voice')' event in nodejs, the nodejs socket emits to the 'socket.on( ...

How to identify the position of an element while scrolling using JavaScript/jQuery

Trying to determine the distance between an element and the top of the window document. After initial value is retrieved during scroll event, it remains unchanged. How can this value be continuously tracked as the page scrolls? JS: $(function() { $(wi ...

module 'next/router' cannot be located or its associated type declarations are missing

Running into some issues with my NextJS application. An unusual error message is appearing, even though my code is functioning smoothly without any errors. import { useRouter } from 'next/router'; // Cannot find module 'next/router' or ...

Tutorial: Implementing InfoWindows for Markers in Google Maps API V3 in a C# Web Page

Here's my newbie question, hope the formatting is correct :) I'm working on an ASP.NET, C# application that retrieves coordinates (Lat, Lon) from SQL and displays them as markers (which is working fine). However, when I try to add infowindow ...

Enhancing React components with dynamic background colors for unique elements

I am encountering an issue while using a map in my code. Specifically, I want to set the background of a particular element within the map. The element I am referring to is "item .title". I aim for this element to have a background color like this: https:/ ...

Using Webpack postcss prefixer with Vue CLI 3

As I work on implementing Bulma CSS in my project using Vue CLI 3, I encounter the need to prefix the classes with webpack. While I found an example of this process, adapting it from a webpack config to vue.config.js poses some challenges. Here is the ini ...

How to implement ngx-spinner in an Angular http subscribe operation

I'm trying to incorporate a spinner into my Angular Application using ngx-spinner. I've come across this library but haven't found enough practical examples on how to use it effectively. Specifically, I want to integrate the spinner with my ...

Is it possible to use jquery to specifically target classes?

I am trying to achieve the following: $('.class.img').css('cellpadding', variable); However, this code does not seem to be working as expected. Despite searching online, I have not been able to find a solution. Any assistance on how to ...

Using TypeScript to work with asynchronous child_process.exec operations

Having trouble implementing a child_process.exec call with TypeScript and finding error handling to be quite challenging. Here's the basic idea of what I'm attempting: import { promisify } from "util"; import { exec, ExecException } fr ...