0

How to convert an array of objects to an array from classes? without a loop?

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

1 Answer 1

3

One way or another, you'll need to call new Lead for each element of arr. Simplest way to do this would probably be with array.map:

let arr = [ {'value': '1'}, {'value': '2'} ];
const leads: Lead[] = arr.map(init => new Lead(init));
Sign up to request clarification or add additional context in comments.

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.