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

Generate a complete screenshot of a website using Chrome 59 through code

Is it possible to programmatically capture a full-page screenshot of a website using the latest Chrome 59 and chromedriver with Selenium Webdriver, even if the website is larger than the screen size? ...

Is there a way to use Lodash to quickly return the same value if a condition is met using the ternary operator

Is there a condensed way to do this using Lodash? (or perhaps Vanilla JS/TypeScript) var val = _.get(obj, 'value', ''); Please note that var val = obj.value || ''; is not suitable as it considers 0 and false as valid but fal ...

Are there any ways to pass an onClick function to a controller in React?

To prevent duplicate numbers from being generated, I added a button that, when clicked by a user, displays a message indicating that the value is being saved to avoid duplicates. However, when attempting to handle this on the server side controller, I enco ...

Slideshow of table rows in HTML

On a webpage, I am populating an HTML table with a random number of rows ranging from 1 to 100. Regardless of the total number of rows, the requirement is to display only 10 rows at a time on the screen and then shift to the next set of 10 rows every 5 sec ...

Tips for adjusting the size and positioning the ng bootstrap carousel in the center

My Angular project is using ng bootstrap, but I'm facing a styling issue. The content doesn't display in the center, rather it appears in the upper left corner: example I would like the content to be centered and wide under the blue headbar. W ...

There seems to be an issue with the pastebin api createPasteFromFile method as it is showing an error of 'create

I'm currently working on a logging system using node for a twitch chat. The idea is that when you type "!logs user" in the chat, it should upload the corresponding user.txt file to pastebin and provide a link to it in the chat. For this project, I am ...

nodemon failing to automatically refresh files in typescript projects

I am currently developing an app using NodeJs, express, typescript, and nodemon. However, I am encountering an issue where the page does not refresh when I make changes to the ts files. Is there a way for me to automatically compile the ts files to js an ...

What could be causing the issue with Google Chart in my ASP MVC app?

My controller has a method that returns Json data. [HttpPost] public JsonResult CompanyChart() { var data = db.adusers; var selectUsers = from s in data where (s.Company != null) select s; int f ...

Dynamic Filtering with jQuery List

I'm attempting to create a dynamic filter list on keypress event. For example, if I type "It" into the input field, the elements that do not match this value will be hidden. I'm unsure if the code structure I have implemented below effectively ac ...

React page is not loading properly after refreshing, displaying unprocessed data instead

Hello everyone! I am currently working on developing an app using Node, React, and Mongoose without utilizing the CRA command, and I have also incorporated custom webpack setup. Initially, I was able to build everything within a single React page (App.jsx ...

The type of a reference variable in a type definition of another variable

Can we reference the type of one variable (let's call it someVar) in TypeScript when declaring the type of another variable (anotherVar)? For example, instead of creating a separate type declaration for { complex: 'type' }, can we directly ...

Combine form data from a reactive form into a string using interpolation

Currently, I am working with an object that has a string property embedded within it. The string in this property contains interpolation elements. For my user interface, I have implemented a reactive form with an input field. My goal is to display the ent ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

Looking for a SSR Component to Choose Dates?

In the process of designing a landing page, I encountered a challenge with incorporating a date picker feature. My goal is to have users select a date and then be redirected to another page upon clicking a button. The technology stack includes NextJS where ...

Assign the default value of a Vue prop to the options of its parent component

I have a child component that needs to accept a value given in the component's parent's $options object as a possible default value. In the background, the component should be able to receive its data through a prop or from a configuration. Howe ...

What is the smallest server.js file needed to run a react/redux application?

I have successfully configured my project using webpack and babel for ES6 transpilation with the specified presets: { "presets": ["react", "es2015", "stage-1"] } My webpack production configuration is structured as follows: var path = require('pa ...

What is preventing me from concealing my input field when its type is set to "file"?

I've been attempting to conceal my input field of a file type, but even with the hidden attribute, it refuses to hide. Interestingly, once I remove type="file", the code successfully hides itself Does anyone have insight on how I can hide ...

Simultaneously sending jQuery.ajax data while submitting a form

I'm facing a bit of a dilemma here. I have a form with multiple fields, including one for entering links. When you input a link and click the add button, the link is added to a link_array using jQuery. My goal is to send this array through the jQuery. ...

How to use the transform function in JavaScript

Hey there, I'm looking to create a new function. I am just starting out with javascript. I want to wrap the code below in a function like: ConfirmDelete() { }; This function should perform the same action as this code snippet: $('.btn-danger ...

Tips for receiving dual return values from an AJAX request

I am sending an array of table IDs to retrieve the table numbers associated with those IDs from the database. I need to add up all the default seats for each table ID and return the total. JAVASCRIPT : function showUser(str) { if ...