0

I have a employee object and i want to copy some of the values in to a new object. I'm using Typescript for to copy them, but i'm getting error.

Typescript code:

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);

Plunker code link:

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

3 Answers 3

2

You need to run that code in a function. Here I'm running it in the constructor. You can only declare variables in the class.

also you need to initialize companies 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);

  }
Sign up to request clarification or add additional context in comments.

Comments

2

There are couple of issues,

you have to write code iside some function

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

and initialize companies property,

Check out updated the Plunker!!

Hope this helps!!

Comments

0

This worked for me:

public employee: any[] = [];
public companies: any[] = [];

ngOnInit() {
    this.employee = [
    { "empId": "59C", "empDesc": "Software","location":"Dallas"},
    { "empId": "AMI", "empDesc": "Hardware", "location":"San Francisco"}
    ];


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.