问题描述
我有一个对象数组,我打算在特定条件下将其中的几个字段复制到不同的对象值
fromPage: "home";
sample = [
{iD:100A,fName:"jack",age:28},{iD:200A,fName:"kate",age:29},{iD:300A,fName:"rose",age:30}
]```
` copyObj = [{id:string,name:string}] `
预期结果:
copyObj = [
{id:100A,name:"jack"},{id:100B,name:"kate"}
]
我想将这些特定字段从示例复制到我的 copyObj。我尝试了以下方式,但最终未定义。
for(var i=0;i<=sample.length;i++){
if(this.fromPage == "home")
{
this.copyObj[i].id = this.sample[i].iD;
this.copyObj[i].name = this.sample[i].fName;
}
}
任何其他方式来实现这一点,请帮助。我还尝试使用 forEach 进行迭代,然后将值推送到新数组,但没有奏效。
解决方法
试试下面的代码,
this.copyObj=[];
for(var i=0;i<=this.sample.length-1;i++){
if(this.fromPage === "home"){
this.copyObj.push({'id':this.sample[i].iD,'name':this.sample[i].fName});
}
}