Typescript: Is there an easy way to convert an array of objects of one type to another?

So I have two classes

Item { name: string; desc: string; meta: string} ViewItem { name: string; desc: string; hidden: boolean; } 

I have an Item array that needs to be converted to a ViewItem array. I am currently browsing an array using, creating an instance of ViewItem, assigning values ​​to attributes and pushing them to the second array.

Is there an easy way to achieve this using lambda expressions? (similar to C #) Or are there other ways?

+6
source share
2 answers

You haven't provided enough of your code, so I'm not sure how you instantiate your classes, but you can use the array of function arrays anyway:

 class Item { name: string; desc: string; meta: string } class ViewItem { name: string; desc: string; hidden: boolean; constructor(item: Item) { this.name = item.name; this.desc = item.desc; this.hidden = false; } } let arr1: Item[]; let arr2 = arr1.map(item => new ViewItem(item)); 

( code on the playground )

+10
source

An alternative method is to use Object.keys ,

 class Item { name: string; desc: string; meta: string } class ViewItem { name: string; desc: string; hidden: boolean; // additional properties additionalProp: boolean; constructor(item: Item) { Object.keys(item).forEach((prop) => { this[prop] = item[prop]; }); // additional properties specific to this class this.additionalProp = false; } } 

Using:

 let arr1: Item[] = [ { name: "John Doe", desc: "blah", meta: "blah blah" } ]; let arr2: ViewItem[] = arr1.map(item => new ViewItem(item)); 

Playground

0
source

Source: https://habr.com/ru/post/1012756/


All Articles