我有一个员工对象,我想将一些值复制到一个新对象中。我正在使用Typescript来复制它们,但我收到了错误。
打字稿代码:
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代码链接:
答案 0 :(得分:2)
您需要在函数中运行该代码。在这里,我在构造函数中运行它。您只能在类中声明变量。
您还需要使用空数组初始化companies
。
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);
}
答案 1 :(得分:2)
有几个问题,
你必须编写代码以及某些功能
constructor(){
for (let c of this.employee) {
this.companies.push({
empDesc: c.empDesc,
empId: c.empId
})
};
console.log("Companies",this.companies);
}
并初始化公司财产,
查看更新后的Plunker!!
希望这会有所帮助!!
答案 2 :(得分:0)
这对我有用:
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);
}