Struggling with transferring data between objects in Angular 2 using typescript?

I am facing an issue with copying values from an employee object to a new object using Typescript. Despite my efforts, I keep encountering errors.

Here is the Typescript code snippet:

employee = [
    { "empId": "59C", "empDesc": "Software","location":"Dallas"},
    { "empId": "AMI", "empDesc": "Hardware", "location":"San Francisco"}
  ];
  companies : any;
  for (let c of this.employee) {
      this.companies.push({
        empDesc: c.empDesc,
        empId: c.empId
      })
    };
  console.log("Companies",this.companies);

For the complete Plunker code, visit the following link:

https://plnkr.co/edit/CnBR4JouNhzH3DWm7QCo?p=preview

Answer №1

To ensure proper execution of the code, it is essential to encase it within a function. In this case, I am executing it within the constructor. Remember that variables can only be declared within the class.

Furthermore, do not forget to initialize the companies variable with an empty array.


  employee = [
    { "empId": "59C", "empDesc": "Software","location":"Dallas"},
    { "empId": "AMI", "empDesc": "Hardware", "location":"San Francisco"}
  ];
  companies : any = [];


  constructor(){
    for (let c of this.employee) {
      this.companies.push({
        empDesc: c.empDesc,
        empId: c.empId
      })
    };
   console.log("Companies",this.companies);

  }

Answer №2

There are a few things to address,

You need to implement the code within a specific function

constructor(){
    for (let c of this.employee) {
      this.companies.push({
        empDesc: c.empDesc,
        empId: c.empId
      })
    };
  console.log("Companies",this.companies);
 }

and ensure the companies property is initialized,

Take a look at the updated version on Plunker!!

I hope this explanation clarifies things!.

Answer №3

This solution worked perfectly in my case:

const staff: any[] = [];
const organizations: any[] = [];

ngOnInit() {
    staff = [
      { "id": "59C", "name": "John Doe", "department":"IT"},
      { "id": "AMI", "name": "Jane Smith", "department":"HR"}
    ];


    for (let s of staff) {
      let temp = [{
        name: s.name,
        id: s.id
      }]
      organizations.push(temp);
    };
    console.log("Organizations", organizations);
}

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

Is it possible to create a distinctive property value within an ngFor loop that operates autonomously across two child components?

I am working on a functionality where, upon clicking on a specific car brand, the name of the person and their favorite car will be displayed at the bottom. However, I'm facing an issue where the car brand is being repeated among all items in the ngFo ...

Implementing data waiting strategy in Vue component using TypeScript for rendering

When working with the first component, I encountered a scenario where I needed to open a new page using the router functionality: In Component_1.vue: let route = this.$router.resolve({ name: 'Schedule', params : { id: (this.schedule[0].schedule ...

TypeScript equivalent to Python's method for removing non-whitespace characters is achieved by

I understand that I can utilize .trim() to eliminate trailing spaces Is there a method to trim non-space characters instead? In [1]: str = 'abc/def/ghi/' In [2]: s.strip('/') Out[2]: 'abc/def/ghi' I am referring to the funct ...

Guide on customizing VS Code's Explorer to display angular js icons

How can you customize the icons displayed in Explorer within VS Code by adding a specific addon procedure? https://i.sstatic.net/KSMwC.png https://i.sstatic.net/2mFMq.png ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

Issue with MUI 5 Button component not receiving all necessary props

Currently, I am attempting to create a customized MUI5-based button in a separate component with the following code: import {Button, buttonClasses, ButtonProps, styled} from '@mui/material'; interface MxFlatButtonProps extends Omit<ButtonProp ...

What could be the reason behind the glob promise yielding an array with empty strings?

I am currently utilizing TypeScript, ts-node, npm, and path modules My objective is to generate an array of file names based on a specific pattern using glob-promise - an npm package I imported that offers promise-based functionality for the glob module. ...

Creating a variety of active button colors using Bootstrap and Angular's ngFor

Is there a way to assign individual colors to each button in a menu with four buttons? I want different colors for the active state and rollover effect of each button. https://i.sstatic.net/3rW0L.png .html <div class="d-flex justify-content-center"&g ...

I am currently working on creating a drag select feature in React completely from scratch, but I'm facing some challenges with

Check out this code I created for drag selection: Here's the item generation code: const items = [ 1, 2, 3, ...94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, ].map((i) => ({ item: i, selected: i === 1 })); This is the actual code responsi ...

What is the most effective method to clean an object in JavaScript while maintaining security?

To circumvent the JavaScript delete operator (source: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/delete), I have opted to utilize object destructuring to eliminate private properties: //sample helper-function in ts const sani ...

Is there a way to ensure that the content of my modal dialog only displays once when it is opened?

While working with Chakra UI, I encountered a unique issue that I hadn't faced before with Material UI. The problem arises when using the Chakra UI modal dialog - all components inside it get rendered twice upon opening. Despite attempting to disable ...

Using Webpack to manage environment variables in Typescript

Having some issues declaring global variables in Typescript with Webpack's DefinePlugin. Seeking assistance to identify what might be going wrong. Implemented an environment variable in my .bash_profile: export API_KEY_GOOGLE_MAPS=xxxxxxxxxxxxxxxx ...

Troubleshoot: Angular 2 Carousel not Showing up on Page

Having trouble understanding why my carousel component is present but none of the CSS or images are showing up. This is my app.component.ts file: import { Component } from '@angular/core'; // Import our Carousel Component import {CSSCarouselCo ...

Utilizing the return value of a MockService in a Jasmine unit test results in test failure

A StackBlitz has been set up with the karma/jasmine loader for you to view test pass/fail results. The application is functioning correctly. All my tests are expected to pass without any issues, but I am encountering an unusual error when using a mockser ...

Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined": https://i.sstatic.net/TvfEr.png This is how my media.component.ts file is structured: impo ...

Guide to configuring a custom "page not found" error page in Spring Boot 2 and Angular

In the previous version of Spring Boot <2, I used to implement the following: @Configuration public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry. ...

"How to incorporate SortableJS into Ionic 3 Angular app with the help of the systemjs.config.js

I'm currently following the instructions on https://github.com/SortableJS/angular-sortablejs and I seem to be facing an issue with the systemjs.config.js file. My app is built using Ionic 3 and Angular 4. To address this, I created a script called sy ...

Issues with exporting function and interface have been identified

When exporting a function and type from the library in the convertToUpper.ts file, I have the following code: export function Sample() { console.log('sample') } export type IProp = { name: string age: number } The index.ts file in my lib ...

Creating a declaration file for a library's entry point involves outlining the structure and types

I have developed an npm library that is made up of several ES6 modules, which are then consolidated into a single js file. The directory structure looks like this: src main.ts one.ts two.ts three.ts types index.d.ts index.ts The index.ts fil ...

Retrieve the variable only once a response has been received from the POST request

Is there a way to update a variable in my component only after receiving a response from a POST request? Here is the code in component.ts: formSubmit() { this.sent = this.submitProvider.sendByPost(this.form); this.formSent = this.submitProvider.f ...