Error: The 'name' property cannot be assigned to an undefined value

Currently facing an issue while trying to assign values from a JSON response to another variable. The error message "Cannot set property name of undefined" is appearing.

export interface Data
{
   description: any;
   name : any;
}

Within the main class, I have defined the following data

actionData : any;
action:Data[]=[];

getData()
  {
      this.spref.getNewData().subscribe(
        response => {
          this.actionData = response;
          for(let i=0;i<this.actionData.length;i++)
          {
             
               this.action[i].name = this.actionData[i].name;
               this.action[i].description = this.actionData[i].description;
          }
    
          })
         
        },
        error => {
          console.log('Failure: ', error);
        }
      );

   }

The format of the actionData response is as follows:

[{
description: "pqrs"
jsonType: "com.xyz.common.object.NewData"
name: "abc"
value: "xyz"
}]

The desired format for storing the action data is:

[{
description: "pqrs"
name: "abc"
}]

Thank you in advance!

Answer №1

action[i] will be undefined if not initialized. Make sure to initialize it before assigning any properties, as shown below:

actionData : any;
action:Data[]=[];

getData()
  {
      this.spref.getNewData().subscribe(
        response => {
          this.actionData = response;
          for(let i=0;i<this.actionData.length;i++)
          {
               this.action[i] = {
                   name: this.actionData[i].name;
                   description: this.actionData[i].description;
               }
          }
    
          })
         
        },
        error => {
          console.log('Failure: ', error);
        }
      );

   }

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

Encountered a problem while trying to retrieve HTML values from an object within a ReactJS component

I have encountered an issue while working with an object that contains HTML values. When trying to access it, I am facing the following error: Element implicitly has an 'any' type because expression of type 'any' can't be used to ...

Top recommendation for parsing a single record from a JSON array

Currently I am fetching the result of a REST method (observable) which typically contains only one element. Although my code is functional and displaying the data, I keep getting an ERROR message in the browser console saying TypeError: Cannot read propert ...

Implementing angular-material-design into an Angular 4 application with the help of Angular CLI

Is there a proper way to use bootstrap-material-design in an Angular 4 app with Angular CLI? In my project, I included the css file in my styles.css like this: @import "~bootstrap-material-design/dist/css/bootstrap-material-design.min.css"; Although I c ...

The act of storing compressed JSON files may result in unexpected connection interruptions

I've encountered an issue where I'm attempting to download a gzipped JSON file, but when trying to read the response content using the requests library, the connection gets reset. data = requests.request("GET", i, stream=True) with gzip.open(i.r ...

Learning how to extract parameters from a GET request in Node.js

I am currently working on creating a GET request using Node.js. The typical GET request sends all database data back as res.json. In the database code, imei.name retrieves a value every time. My goal is to create a GET method that will only return a specif ...

What is the best way to save values from an input field to a temporary array and then showcase them in a list using Angular 2?

One of the challenges I'm facing is incorporating an input field into my form. This input field is specifically for capturing contact numbers. Users should have the ability to add multiple contact numbers without the need for separate fields. Hence, ...

Defining function parameter type in TypeScript based on another parameter

I'm currently working on a Chrome extension and I want to inject code into the page. However, I'm unsure how to achieve this without specifying fun: any and arg: any. type funs = typeof getPageInfo | typeof setPercen; async function injectScript ...

Creating CSS from Angular stylesheets?

Are there any methods available to view the CSS corresponding to SCSS when using SCSS as the preprocessor for Angular? You can find a solution here: When using angular with scss, how can I see the translated css? The answer suggests using the --extract-c ...

Error TS2339: The property 'mock' is not found on the type '(type: string) => Promise'. Unable to create a mock for SQS Queue.sendMessage()

I am attempting to simulate a call to the SQS method sendMessage() that is used in the System Under Test (SUT) like this: private async pushJobIntoQueue(network: Network) { await this.contactInteractionsQueue.sendMessage( JSON.stringify({ ...

Struggling with the relative path in Angular 2 components

My settings can be found below. I wanted to utilize relative paths for the component, but unfortunately, I am encountering this issue: Error: 404 GET /js/some.component.html I am currently utilizing SystemJS. some.component.ts import { Component, OnI ...

Is there a way to adjust the StatusBar color or make it transparent on Android when working with NativeScript and Angular?

I am having trouble changing the StatusBar color in my NativeScript with Angular project. It currently appears as translucent black, darkening the background behind it. I want to either make it transparent or match the background color of the page. What I ...

Angular 10.1: "The constructor did not align with Dependency Injection."

I am facing an issue in my project where I attempted to move the spinner service out from my components. Now, I am encountering an error message that says Error: This constructor was not compatible with Dependency Injection.. Surprisingly, the VSCode linte ...

Updating a multitude of values efficiently

When updating multiple fields using ajax, I retrieve a row from the database on my server, JSON encode the row, and send it as the xmlhttp.responseText. The format of the response text is as follows: {"JobCardNum":5063,"IssueTo":"MachineShop","Priority": ...

Angular8 is displeased with the unexpected appearance of only one argument when it was clearly expecting two

Even though I have declared all my requirements statically in my component.html file, why am I receiving an error stating "Expected 2 arguments but got 1"? I use static concepts, so it's confusing to encounter this type of error. Below you can see th ...

Troubleshooting ngFor usage with Object Arrays in Angular 2

I have created an Array of Objects in my Component class as shown below : deskCategories : Array<any>; this.deskCategories = [ { catLabel : 'Tools', catIcon : 'suitcase' }, { ...

Ways to earn points through a JSON Request

I need assistance drawing a polyline along the most efficient route between two locations. There are multiple points to consider between the starting point and the destination. Could someone provide guidance on extracting points for the polyline using JS ...

Feature to insert a fresh row into SAPUI5 table

I've been attempting to insert new rows into a SAPUI5 table with the click of a button. Despite watching numerous tutorials online, I haven't found one that fits my specific situation. Currently, the JSON data is loaded via a mock server with th ...

Struggling with CORS Error in Spring Boot/Angular application?

Error message: https://i.sstatic.net/50emd.png Issue found in Security Configuration with @CrossOrigin http.cors(cors->cors.configurationSource(apiConfigurationSource())) @Bean CorsConfigurationSource apiConfigurationSource() { CorsCo ...

When using JSON.stringify(value, replacer), the output may vary between Chrome and Firefox

I'm encountering an issue when attempting to utilize JSON.stringify with the "replacer" function. var scriptTag = document.createElement('script'); scriptTag.type = 'text/javascript'; scriptTag.src = 'https:// ...

What is the best method to reset an array and session variable to an empty state when the browser is refreshed?

Is there a way to reset an array containing a $_SESSION variable back to blank every time the browser is refreshed? Currently, if I upload files and then refresh the browser, the array still contains the names of the previously uploaded files. How can I en ...