Combine values within a loop and transform them into an object using TypeScript

Being new to typescript, I am unsure how to map values inside a loop. I have a function that performs some logic and returns a number. This function will be called in another function to return two values: a number and a string.

export class matrix {

     public pattern!: {[key: string]: number[]};

     // The function will be called within a loop in another function
     public setPattern(data: number, category: string): void {

         // Logic is implemented here to set row as a value
         const row = 10; // just a random value
 
         this.pattern[category].push(row); // not functional at the moment
     
     } 
}
     
// Expected output structure  
{
    "some category": [10,55,4,53,1],
    "more rows": [1,2,8]
} 

Answer №1

When the function is called for the first time, the pattern remains undefined, causing an error when trying to add a key to undefined this.pattern[catergory].

export class matrix {
    public pattern: {[key: string]: number[]} = {};
    public setPattern(data: number, catergory: string): void {
        const row = 10;// value chosen randomly
        this.pattern[catergory].push(row);// will not work correctly
    } 
}
   

Answer №2

It may not work if the array is not already initialized

Make sure to add this line before pushing a new element:

if(this.pattern[category] == undefined) this.pattern[category] = []

Then, once the array is initialized, you can push the new element into it like so:

this.pattern[category].push(row);

Additionally, ensure that the pattern object is properly initialized:

public pattern!: {[key: string]: number[]}; = {}

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

The functionality of cropping is not supported within a Bootstrap modal

I have been using ngimgcrop successfully to crop images within my application. However, I encountered an issue when trying to display the cropped images inside a uibmodal (AngularJS modal). Despite trying various solutions, such as using ng-init, I was una ...

Is it possible to verify a file's type with Nestjs Pipes and the FileTypeValidator?

I am facing an issue with implementing a Nestjs route in a controller that includes a file upload using Multer. The goal is to edit a user's profile picture, so I need to validate that the uploaded file is an image. However, despite using the FileType ...

Why does this vow continue to linger unresolved?

I've been experimenting with a code that involves adding promises to a queue for processing in a non-blocking manner. One code snippet behaves as anticipated while the other doesn't, leaving me puzzled. Problematic Code: const axios = require(&a ...

Methods for organizing consecutive elements within an array in Javascript/Typescript

Let's explore this collection of objects: [ { key1: "AAA", key2: "BBB" }, { key1: "BBB", key2: "CCC" }, { key1: "CCC", key2: "DD ...

Encountering npm3 installation errors with typyings in Angular 2?

Each time I try to sudo npm install Angular 2 modules, everything updates and installs correctly. However, I encounter the following error when the typings install is attempted: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0 ...

Tips for expanding third-party classes in a versatile manner using Typescript

tl;dr: Seeking a better way to extend 3rd-party lib's class in JavaScript. Imagine having a library that defines a basic entity called Animal: class Animal { type: string; } Now, you want to create specific instances like a dog and a cat: const ...

Utilize the HTTP path to designate the currently active tab

Here is a sample code snippet for vertical tabs in React using the Material-UI library: import * as React from 'react'; import Tabs from '@mui/material/Tabs'; import Tab from '@mui/material/Tab'; import Typography from '@ ...

File resolution issue with TypeScript

While I am aware that using TypeScript outFile is generally advised against, I currently have no choice but to utilize it until a more suitable solution like AMD can be implemented. It seems like there may be a "module splitting issue" in my project. In t ...

Creating a web application using Aframe and NextJs with typescript without the use of tags

I'm still trying to wrap my head around Aframe. I managed to load it, but I'm having trouble using the tags I want, such as and I can't figure out how to load a model with an Entity or make it animate. Something must be off in my approach. ...

Angular: monitoring changes in HTML content within a Component or Directive

I have a situation where I am retrieving HTML content from a REST endpoint using a directive and inserting it into a div element using [innerHTML]. Once this HTML content is rendered, I would like to manipulate it by calling a global function. My approach ...

Shrink the size of the fixed navigation menu

I am experiencing a significant issue with a fixed menu when the browser is resized, as the list items are overlapping and extending beyond their defined section. It's quite frustrating :(. I have been considering two possible solutions: 1: Set a fixe ...

The error "500 window is not defined in Nuxt3 when using the composition API"

Is it possible to detect the user's preference for color scheme and set a data-mode attribute on the document root (html)? I've been struggling with this. In my app.vue code, I have the following: <template> <div> <NuxtLayout /> ...

The scrolling feature induces a contraction to the left side

Recently, I implemented the code below to fix my menu when scrolling the page: var num = 5; $(window).bind('scroll', function () { if ($(window).scrollTop() > num) { $('.scroll').css({'position':'fixed&apo ...

Execute a personalized function when an array is updated or created in JavaScript

I have experience in adding custom properties to objects. For example, if I have a method called foo, const foo = () => { console.log('custom method'); } I can add the foo method to the Array prototype and use it with array variables by Arra ...

The attribute cannot be found within the string or object typescript

Encountering the error: Property 'p' does not exist on type 'string | { p: string; }'. Can someone assist me in resolving this issue? interface x{ n:string | {p:string} } function text(args:x){ const {n:{p}}=args; console.l ...

Bug in Async.js causes unexpected results in loop involving numbers

When attempting to reference a variable in a for loop using the Async Library for Node.js, it seems to not work as expected. Here is an example: var functionArray = [] , x; for(x = 0; x < 5; x++) { functionArray.push(function (callback) { conso ...

Comparing fields within arrays of objects using JavaScript ES6 and higher versions

Feeling stuck in a loop here. The concept seems straightforward, but JavaScript is really giving me a hard time. I have two arrays of objects: let allProfileUsers = [ { id: "0b4cd920-31da-11ec-a31c-cd844bfb73be", auth_user_id ...

What is the best way to align the ul, li, and span elements in a single row?

To display the 'previous' on the left side of the list item and the 'next' on the right side, aligned in a single line, how can this layout be achieved? <ul style= 'list-style-type: none;' class="filter1"> <li&g ...

Issues with slow performance on Android webview are causing frustration for

Currently developing a game using JavaScript. The app performs smoothly on my browser (efficient), however, encountering difficulties when attempting to run it through an android webview. The app takes about 5 seconds or more to start up (which feels kin ...

Executing Multiple Ajax Requests in Jquery

I have a jQuery script that is designed to submit data to the database: //delegated submit handlers for the forms inside the table $('#issue').on('click', function (e) { ...