Unable to assign a value to an undefined property in TypeScript

I need to store data in an object and then add it to another object

let globalSamples = {} as any;
let sample = { } as ISamplesDetail [];
sample = [];
for (let i = 0 ; i<this.prelevementLingette.samplesDetail.length; i++)
    {
      sample [i].id= this.old.samplesDetail[i].id;
      sample [i].reference=this.old.samplesDetail[i].reference;
}
globalSamples.push(sample);

I encountered the error message

'Cannot set property 'reference' of undefined'

What steps should I take to fix this issue?

Answer №1

Your code has some issues that I've addressed and cleaned up for you.

// Defining the globalSamples array with proper type
const globalSamples: ISamplesDetail[][] = [];

// Declaring a constant sample array to avoid reassignment 
const sample: ISamplesDetail[] = [];

// loop through 'this.prelevementLingette' rather than 'this.old'
for (let i = 0; i < this.prelevementLingette.samplesDetail.length; i++) {
      sample[i] = {
          id: this.old.samplesDetail[i].id,
          reference: this.old.samplesDetail[i].reference
      }
}

// Adding the sample array to the globalSamples array
globalSamples.push(sample);

It appears that there may be some logic confusion in your code, but without more context it's difficult to provide specific advice.

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

A method for transferring information stored in chrome.storage to a variable within an Angular component

How can I effectively assign data fetched from chrome.storage.sync.get to my Angular component's variable? Below is the code snippet of my component: export class KTableComponent implements OnInit { words: string[] = []; constructor() { } ...

Angular dynamically filling in a table with incomplete object data

I am currently working on a scientific project that involves displaying large amounts of data in tables. The experiments I'm working with have timestamps that follow this format: interface TimeData { time: string; data: {SD: string, SEM: string ...

Unfortunately, the utilization of an import statement outside a module is restricted when working with Electron

Is there a solution to the well-known problem of encountering the error message "Cannot use import statement outside a module" when working with an Electron-React-Typescript application? //const { app, BrowserWindow } = require('electron'); impor ...

Obtain the Enum's Name in TypeScript as a String

I am currently looking for a solution to transform the name of an enum into a string format. Suppose I have the following Response enum, how can I obtain or convert 'Response' into a string? One of my functions accepts any enum as input and requi ...

Error: The function to create deep copies of objects is not working properly due to TypeError: Object(...) is not a

Encountering a TypeError: Object(...) is not a function in the following situation: To set up the state of a component with a specific Article (to be fetched from the backend in componentDidMount), I am implementing this approach // ArticlePage.tsx import ...

Modifying a property in a nested layout through a page in Next.js 13

Currently, I am facing a challenge in updating the page title within a nested layout structure. app/docs/layout.tsx: export const DocsLayout = ({children}:{children: React.ReactNode}) => { return ( <> <header> ...

NgFor is designed to bind only to Iterables like Arrays

After exploring other questions related to the same error, I realized that my approach for retrieving data is unique. I am trying to fetch data from an API and display it on the page using Angular. The http request will return an array of projects. Below ...

Generating Pulumi Outputs for exporting as an external configuration file

I am currently utilizing Cloudrun in GCP and am interested in summarizing the created APIs with API Gateway. To achieve this, a Swagger/OpenAPI v2 document needs to be generated containing the google-generated URLs for the Cloudrun Services. How can I ext ...

Using TypeScript with React: Step-by-step guide to creating a ref prop

I'm currently using Ionic with React (typescript) and working on creating my custom form builder. Within this process, I've created a form that requires a ref property for referencing purposes when in use. My challenge lies in defining a prop tha ...

JSX conditionally rendering with an inline question: <option disabled value="">Select an option</option>

Yes, I can confirm that the inline is functioning properly because in the Convert HK to Passive Segment paragraph at the top I am seeing the expected output. What I am aiming for is to display a "Choose a hotel" message when there are multiple hotels in th ...

AWS Amplify is failing to maintain the user session post a successful login

Currently, I am developing an aws-serverless application using React. My main issue lies in the authentication process with aws-amplify. The authentication works smoothly, but the session is not being preserved. During the signing-in stage: await Auth.s ...

It appears that React Native's absolute paths are not functioning as expected

I have been attempting to set up React Native with absolute paths for easier imports, but I am having trouble getting it to work. Here is my tsconfig.json: { "compilerOptions": { "allowJs": true, "allowSynthetic ...

Tips for implementing assertions within the syntax of destructuring?

How can I implement type assertion in destructuring with Typescript? type StringOrNumber = string | number const obj = { foo: 123 as StringOrNumber } const { foo } = obj I've been struggling to find a simple way to apply the number type assertio ...

What is the best way to send multiple data using GetServerSideProps?

I have a challenge where I need to pass multiple sets of sanity data into a component, but I am restricted to using getServerSideProps only once. How can I work around this limitation to include more than one set of sanity data? pages > members.tsx exp ...

Converting JSON to TypeScript in an Angular project

Within my Angular project, I have an HTTP service that communicates with a web API to retrieve JSON data. However, there is a discrepancy in the naming convention between the key in the JSON response (e.g., "Property" in uppercase) and the corresponding pr ...

What does it signify when it is stated that "it is not a descendant of the indexer"?

Currently, I am diving into Typescript with the help of this informative guide on indexer types. There is a specific piece of code that has me puzzled: interface NumberDictionary { [index: string]: number; length: number; // okay, length shoul ...

Deactivate the button if the mat-radio element is not selected

Here is my setup with a mat-radio-group and a button: <form action=""> <mat-radio-group aria-label="Select an option"> <mat-radio-button value="1">Option 1</mat-radio-button> <mat-radio-b ...

What is the best way to globally incorporate tether or any other feature in my Meteor 1.3 TypeScript project?

I've been working hard to get my ng2-prototype up and running in a meteor1.3 environment. Previously, I was using webpack to build the prototype and utilized a provide plugin to make jQuery and Tether available during module building: plugins: [ ne ...

Trouble encountered with uploading files using Multer

I am facing an issue with uploading images on a website that is built using React. The problem seems to be related to the backend Node.js code. Code: const multer = require("multer"); // Check if the directory exists, if not, create it const di ...

Challenges arise with data updating following a mutation in @tanstack/react-query

As I work on building an e-commerce website using React, I have a specific feature where users can add products to their favorites by clicking a button. Following this action, I aim to update the profile request to display the user's information along ...