如何将对象数组从类转换为数组? 没有循环?
https://repl.it/repls/YellowSuperficialHexagons
export class Lead {
public value = 'val';
public constructor( init?: Partial<Lead> ) {
Object.assign(this, init);
}
public printOk(){
return this.value + ' ok';
}
}
let arr = [ {'value': '1'}, {'value': '2'} ]
let lead: Lead = new Lead(arr[0]);
console.log(lead.printOk());
const leads:Partial<Lead>[] = arr;
console.log(leads[0].value);
//console.log(leads[0].printOk()); //error
答案 0 :(得分:4)
一种或另一种方式,您需要为arr
的每个元素调用新的Lead。最简单的方法可能是使用array.map:
let arr = [ {'value': '1'}, {'value': '2'} ];
const leads: Lead[] = arr.map(init => new Lead(init));