Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Is there a simple 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 array of Item that needs to be converted into an array of ViewItem. Currently, I am looping through the array using for, instantiating ViewItem, assigning values to attributes and pushing it to the second array.

Is there a simple way to achieve this using lambda expressions? (similar to C#) Or is there any other means?

like image 464
Shilpa Nagavara Avatar asked Nov 30 '16 12:11

Shilpa Nagavara


People also ask

How do I convert one object to another in TypeScript?

The Typescript generally it converts one data type to another data type by using the cast operation. We can convert all types of datas are converted from one type to another type like that cast object is one of the features for to convert the object type of values to another type.

How do you push an array of objects into another array in TypeScript?

Use the concat function, like so: var arrayA = [1, 2]; var arrayB = [3, 4]; var newArray = arrayA. concat(arrayB); The value of newArray will be [1, 2, 3, 4] ( arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).


2 Answers

You haven't showed enough of your code, so I'm not sure how you instantiate your classes, but in any case you can use the array map function:

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 in playground)


Edit

This can be shorter with Object.assign:

constructor(item: Item) {     Object.assign(this, item); } 
like image 197
Nitzan Tomer Avatar answered Sep 19 '22 09:09

Nitzan Tomer


you can do use something like this.

const newdata = olddata.map((x) => {         return { id: Number(x.id), label: x.label };       }); 

as the converted column will be mapped to the newdata array.

like image 23
ammad khan Avatar answered Sep 22 '22 09:09

ammad khan