Using TypeScript to assign string array values to object properties

I am working with a string array:

values: string['myName', 'myLastname', 'myAge']
and my goal is to assign each value to a property of an object like this:
myModel={name:'', lastname:'', age:''}
one by one. I attempted to write the code as follows:

let i =0;
Object.keys(this.myModel).forEach((key) => {
    this.myModel[key] = this.values[i];
    i++;
  });

Unfortunately, I encountered an error. Can you help me fix it?

Answer №1

Instead of declaring and using i for index, you can utilize forEach on object keys with the second parameter:

Object.keys(this.myModel).forEach((key,i) => {
    this.myModel[key] = this.values[i];
});

Avoid using:

values: string['myName', 'myLastname', 'myAge'];

and opt for:
values: string[] = ['myName', 'myLastname', 'myAge'];

Other than that, your code appears to be functioning properly - although it could vary based on the IDE you're utilizing if it triggers an error. So consider making these adjustments.

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 boolean variable is returning as undefined after being called from a different component

There are 2 parts - the header and login components. If the loginU function returns true, I want to display a logout button in the header component. However, in the console, it shows that the boolean value is undefined in the header component. Login Compo ...

Is it possible for moduleNameMapper to exclude imports made by a module located within node_modules directory?

I am trying to figure out how to make my moduleNameMapper ignore imports from the node_modules directory. The issue is that one of the dependencies, @sendgrid/mail, uses imports starting with ./src/ which causes problems when importing into Jest. My curre ...

Troubleshooting Puppeteer compatibility issues when using TypeScript and esModuleInterop

When attempting to use puppeteer with TypeScript and setting esModuleInterop=true in tsconfig.json, an error occurs stating puppeteer.launch is not a function If I try to import puppeteer using import * as puppeteer from "puppeteer" My questi ...

Getting the logged in user's ID in Angular using MongoDB and Node.js for the backend

How can I retrieve the logged user's ID so that when they click on "My profile", they are directed to url/profile/theirId? Thank you for your help! Below is my authentication.service code: export interface UserDetails{ username: string email: stri ...

Using the routing module to redirect traffic

I've implemented a login page that redirects to a dashboard upon successful login. The dashboard also contains child pages. My requirement is that when a user is logged in and clicks on the logo, they should be redirected to the dashboard. If not logg ...

It is not possible to install Angular CLI on a Mac computer

My Mac computer is currently running macOS Ventura 13.1 I managed to install node (v18.12.1) & npm (8.19.2) successfully on the system. However, when I attempted to run npm install -g @angular/cli to install Angular CLI, it resulted in the following e ...

What could be causing the absence of data from my API on my HTML page?

I've been working on fetching data from my database using an API in Angular, but I'm facing an issue where the data is not being displayed on the HTML component. Although I can see that the data is being fetched through the console and the HTML p ...

Grouping elements of an array of objects in JavaScript

I've been struggling to categorize elements with similar values in the array for quite some time, but I seem to be stuck Array: list = [ {id: "0", created_at: "foo1", value: "35"}, {id: "1", created_at: "foo1", value: "26"}, {id: "2", cr ...

What is the best way to show the previous month along with the year?

I need help with manipulating a date in my code. I have stored the date Nov. 1, 2020 in the variable fiscalYearStart and want to output Oct. 2020. However, when I wrote a function to achieve this, I encountered an error message: ERROR TypeError: fiscalYear ...

How to update the tsconfig.json file within a VS2019 project using MSBuild?

I am working with a Visual Studio solution that contains multiple tsconfig.json files and I would like them to have different behaviors in production. My plan is to create two additional files for this purpose: tsconfig.json will contain the default sett ...

Developing an Angular filter using pipes and mapping techniques

I am relatively new to working with Angular and I have encountered a challenge in creating a filter for a specific value. Within my component, I have the following: myData$: Observable<MyInterface> The interface structure is outlined below: export ...

Creating a customizable table in Angular with resizable columns that can retain their width and size preferences

I'm in the process of creating an Angular application that allows users to add or remove columns based on their preference and priority. My goal is to design a table with resizable column widths and save the adjusted column width in local storage so ...

Instructions for displaying emotes and UTF-8 characters in a Flutter/Java app

In my efforts to display text in Flutter, I am facing the challenge of ensuring that the text is encoded in UTF-8 and can also show emojis. Unfortunately, I have not been successful in achieving both simultaneously. When attempting to decode an input with ...

Error: ngModel does not reflect dynamic changes in value

After calling a Spring service, I am receiving JSON data which is stored in the "etapaData" variable. 0: id: 266 aplicacao: {id: 192, nome: "Sistema de Cadastro", checked: false} erro: {id: 220, nome: "Falta de orçamento", checked: false} perfil: {id: 8, ...

React development: How to define functional components with props as an array but have them recognized as an object

While trying to render <MyComponent {...docs} />, I encountered the following error: TypeError: docs.map is not a function Here's how I am rendering <MyComponent /> from a parent component based on a class: import * as React from &apo ...

Exploring the method of retrieving nested JSON objects in Angular

When my API sends back a JSON response, my Angular application is able to capture it using an Interface. The structure of the JSON response appears as follows: { "release_date":"2012-03-14", "genre_relation": ...

Oops! Looks like there was an error trying to assign the value "$event" to the template variable "element". Remember, template variables can only be read

Can anyone assist me in identifying the issue with this code? <div *ngFor="let element of list; let index=index"> <mat-form-field> <input matInput type="string" [(ngModel)]="element" name="element ...

How can one effectively monitor the advancement of a file transfer operation?

Looking at integrating a Spring Boot REST API with an Angular Frontend, I am interested in monitoring file upload/download progress. I recently came across an informative article that dives into the implementation details of this feature. The approach see ...

Run a script in a newly opened tab using the chrome.tabs.create() method

Struggling with executing a script using chrome.tabs.executeScript() in the tab created with chrome.tabs.create()? Despite searching for solutions, nothing seems to be working as expected. Check out my current code below: runContentScript(){ c ...

Using the `npm install -g @angular/cli` command will not actually install the Angular CLI

I've set out to create a sample Angular2 web app, starting with the installation of Node.js (v 7.1.0) and NPM (v 3.10.9). However, when I try to install Angular CLI by executing 'NPM install -g @angular/cli' in the system command prompt, I e ...