What could be causing my object property to be undefined when used in an if statement?

My attempt to search through an array using a for loop is not yielding the expected results.

      let matrix = [];
      for(let i=0; i<this.row; i++){
        for(let j=0; j<this.column; j++){
            if(this.grid[i][j].name != ""){
              matrix.push(this.grid[i][j].name);
              console.log(matrix);
            }
        }

However, I encounter an issue where I receive an error stating that this.grid[i][j].name is undefined. Surprisingly, when I adjust the condition as follows:

      let matrix = [];
      for(let i=0; i<this.row; i++){
        for(let j=0; j<this.column; j++){
            if(this.grid[i][j]){
              matrix.push(this.grid[i][j].name);
              console.log(matrix);
            }
        }

I check for the existence of an object and then proceed to push the name property into the variable matrix. Oddly enough, the property this.grid[i][j].name appears to be defined in this scenario. However, I am left wondering why it is not defined within the if statement?

Answer №1

I recommend using the following method

 let array = [];
      for(let x=0; x<this.row; x++){
        for(let y=0; y<this.column; y++){
            if(this.grid[x][y] && this.grid[x][y].title){
              array.push(this.grid[x][y].title);
              console.log(array);
            }
        }

This technique allows you to verify the presence of this.grid[x][y] before checking for this.grid[x][y].title

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

Leveraging third-party libraries within an Angular 2+ project powered by webpack

I am a beginner in Angular 2 and currently working on a new client-side application generated using angular2 cli (with webpack2). I need to utilize the splunkjs object from an external library, which can be found at https://github.com/splunk/splunk-sdk-jav ...

Ways to check the functionality of the secondary tier in the api.send method

Currently, I am testing a function that involves returning a promise and subsequently calling the same function again at a second level. However, I am facing difficulties in accessing this second level of call. Below is the function code: itemToForm = () ...

What is the best way to pass data between sibling components using services?

I'm looking to connect a service to a component that can fetch data, share objects, and communicate with other components that are already linked to the database. I've established a service named DashService as follows: import { Injectable } fro ...

Clarifying the concept of invoking generic methods in TypeScript

I'm currently working on creating a versatile method that will execute a function on a list of instances: private exec<Method extends keyof Klass>( method: Method, ...params: Parameters<Klass[Method]> ) { th ...

Transform webservice data into TypeScript object format, ensuring mapping of objects from capital letters to camel case

Something peculiar caught my attention in my Angular2 TypeScript project. When objects are fetched from a web service, they have the type "Level" and the properties are in Pascal case. However, during runtime, I noticed that the properties of these Levels ...

How can I retrieve elements from an array that match a certain criteria and update the corresponding objects in

When an array contains matching IDs, the goal is to merge these objects into one object without affecting the original array. The current code only returns matching objects, but the expected result should combine them as described. main.ts const arr = [{ ...

Error: The authentication state for auth0 is not valid

I'm currently working on integrating auth0 into my angular 5 application by following a tutorial found at: The registration process is functioning correctly, but I encounter an issue when attempting to log in. Upon logging in, the console displays th ...

Bringing in numerous modules within Angular

Currently, I am in the process of developing an application using Angular 4 and Angular Material. Each Material directive necessitates importing its module individually. For instance, when working on a navigation bar, the nav.module.ts file begins to take ...

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

Add a fresh item into an array in Json between existing elements

After looping through a JSON object using foreach, the output is as follows: {"Comment": {"id":"1","post_id":"31","created":"14263241"} , "User": {"fname":"Test","lname":"Test2"} } {"Comment": {"id":"2","post_id":"32","created":"14263257"} , "User": {"f ...

Unable to fetch data from URL in Angular using the HttpClientModule

I have a goal in my application to retrieve data from the following URL and showcase it within the app: https://jsonplaceholder.typicode.com/posts/1 The issue I'm encountering is that the data is not being displayed in my app. The console is showing ...

Accessing information from an NGRX repository and initiating a fresh directive

While I have familiarity with AngularJS and some exposure to Angular, I am relatively new to RXJS and NGRX which has led to some challenges. My NGRX setup closely follows the example project recommended by the NGRX team (https://stackblitz.com/run). The C ...

The importance of handling undefined values in TypeScript and React

There is a condition under which the IconButton element is displayed: {value.content && <IconButton aria-label="copy" onClick={() => copyContent(value.content)}> <ContentCopy /> </IconButton> } However, a ...

Tips for effectively managing index positions within a dual ngFor loop in Angular

I'm working on a feedback form that includes multiple questions with the same set of multiple choice answers. Here's how I've set it up: options: string[] = ['Excellent', 'Fair', 'Good', 'Poor']; q ...

What causes the failure of `click()` on a WebElement?

I am currently utilizing protractor within an angular application. The page model I have is structured as follows: export interface TileElement { idx: number; icon: string; title: string; element: WebElementPromise; } getModels() { //used as wfc. ...

Call a function within another function of the same class in Angular2, and utilize the properties of the first function in the

I am working on a class that contains two functions, both of which retrieve data from API calls. Let's start with the First function getQuotes(){ this.quoteService.getQuotes() .subscribe( quotes => { this.quotCode = this.quo ...

Angular Azure reports that the assets/appconfig.production.json file is missing

I am currently operating a basic single page application where the backend and frontend are hosted separately on Azure. I have "assets": [ "src/assets", "src/favicon.ico", "src/we ...

The discrepancy in the array leads to a result of either 1 or an undetermined

Array x = [3,5,7,9,1] Array y = [3,7,8] z = x - y this should result in z = [5,9,1] (7 is common but I want it excluded) Below is the code snippet: function arrayDifference(x, y) { var arr = []; var difference = []; for (var i = 0; i<x.length& ...

Steps for resetting the ng-multiselect-dropdown

Is it necessary to wrap the ng-multiselect-dropdown in a form in order to reset it? code - app.component.html <div> <p id = "node">Select a Root API Object - </p> <p style="width:50%"> <ng-multiselect-dropdown [placeho ...

How can I retrieve the index of an element within a 2D array using JavaScript when the array is displayed on a webpage?

https://i.stack.imgur.com/GHx9p.png I am currently working on developing an Othello game board within an HTML page using Angular. The board itself is constructed from a 2D number array which I then display using the <table> tag on the webpage. Below ...